Creating kernel density plots

Let's create a kernel density plot for patient height. The kernel density plot is essentially a smoothed version of a histogram. A full discussion of kernel density plots is beyond the scope of this book, but for many applications they provide a viable alternative to the histogram. We use a bin width of 5 cm, though we could try other bin widths. Enter the following syntax:

qplot( HEIGHT, data = T,   geom = "density",  binwidth = 5, xlab = "HEIGHT (cm)", ylab = "DENSITY")  

The kernel density plot looks like this:

Creating kernel density plots

In a kernel density plot, the height of the curve gives an estimate of the probability density at the given value along the horizontal axis.

To shade underneath a density plot, you can use the polygon() command. In the following example, we will illustrate how this is done in base graphics. Here, we select a light green color and use the default smoothing (that is, we do not specify a bin width). Enter the following syntax:

plot(density(HEIGHT), xlab = "HEIGHT (cm)", ylab = "DENSITY", main = "HEIGHT DENSITY PLOT") 
 
polygon(density(HEIGHT), col="#66FF99", border="darkgreen")

We get this graph:

Creating kernel density plots

The polygon() command has shaded under the curve exactly as we wished.

Now let's see how shading is done in qplot. We create a kernel density plot for height, grouped by gender and mapped to our own choice of color. We add transparency in order to make the plot easy to interpret. The fill argument gives a second method of shading under a density plot. Enter the following syntax:

Y <- qplot(HEIGHT, data=T, geom="density", fill=factor(GENDER), alpha=I(0.5), main="Height by Gender", xlab="Height (cm)", ylab="Density ")

Y + scale_fill_manual(values = c("red", "yellow"))

Now the graph looks like this:

Creating kernel density plots

Note that the overlapping area of the two plots has its own color. In this case, the overlapping area is colored orange.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset