Section 18 One Numeric: geom_density

The function geom_density computes kernel density estimates.

18.1 Example 1:

data(iris)

?geom_density

# geom_density

g <- ggplot(data=iris, mapping=aes(Sepal.Length))
g <- g + geom_density()
g

# fill & colour

g <- ggplot(data=iris, mapping=aes(Sepal.Length))
g <- g + geom_density(fill='lightblue', colour='purple')
g

# alpha, labs, theme_bw()

g <- ggplot(data=iris, mapping=aes(Sepal.Length))
g <- g + geom_histogram(mapping=aes(y=..density..),
                        binwidth=0.10, fill='white', colour='blue')
g <- g + geom_density(alpha=0.2, fill='lightgreen', colour='purple')
g <- g + labs(title='Histogram & Density plot of Sepal Length',
              subtitle='Based on Iris data',
              x='Sepal Length (cm)',
              y='Density')
g + theme_bw()

18.2 Example 2:

data(warpbreaks)

  • Draw a density plot of the variable breaks

  • Discuss the density plot

  • Transform the data using log-transformation and redraw the density plot

  • Overlay the histogram and density plot for the data