Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Visualizing the density of a numeric variable


The density plot is mostly used to compare distributions of two numeric variables or a single numeric variable over the category of other variables. In this recipe, we will produce a density plot using the ggplot2 library.

Getting ready

To display the density, we will recall ggplotdata here and will use the disA variable to display the density plot.

How to do it...

To create a density plot, the basic code is as follows:

ggplot(data=ggplotdata,aes(x=disA))+geom_density()

The following figure shows us the visual output of the preceding code:

How it works…

The basic command is the same with ggplot(), but the main visualization is produced by the geom_density() part of the function.

There's more...

With the basic command, we can use another argument to modify the original visualization, such as the color and fill, and we can add other layers to the plot as well.