stat_density(mapping = NULL, data = NULL, geom = "area", position = "stack", adjust = 1, kernel = "gaussian", trim = FALSE, na.rm = FALSE, ...)
density for detailsdensity for detailsTRUE, the default, densities are
trimmed to the actually range of the data. If
FALSE, they are extended by the default 3
bandwidths (as specified by the cut parameter to
density)FALSE (the default), removes
missing values with a warning. If TRUE silently
removes missing values.aes or aes_string. Only
needs to be set at the layer level if you are overriding
the plot defaults.layer. This can include aesthetics whose
values you want to set, not map. See layer
for more details.data.frame with additional columns: densitydensity estimate countdensity * number of points - useful for stacked density plots scaleddensity estimate, scaled to maximum of 1
1d kernel density estimate.
stat_density understands the following aesthetics (required aesthetics are in bold):
x
fill
y
# Scale so peaks have same height: m + geom_density(aes(fill=factor(Drama), y = ..scaled..), size=2)
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
# Make a volcano plot ggplot(diamonds, aes(x = price)) + stat_density(aes(ymax = ..density.., ymin = -..density..), fill = "grey50", colour = "grey50", geom = "ribbon", position = "identity") + facet_grid(. ~ cut) + coord_flip()
# Stacked density plots # If you want to create a stacked density plot, you need to use # the 'count' (density * n) variable instead of the default density # Loses marginal densities qplot(rating, ..density.., data=movies, geom="density", fill=mpaa, position="stack")
# Preserves marginal densities qplot(rating, ..count.., data=movies, geom="density", fill=mpaa, position="stack")
# You can use position="fill" to produce a conditional density estimate qplot(rating, ..count.., data=movies, geom="density", fill=mpaa, position="fill")
# Need to be careful with weighted data m <- ggplot(movies, aes(x=rating, weight=votes)) m + geom_histogram(aes(y = ..count..)) + geom_density(fill=NA)stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this. Warning message: sum(weights) != 1 -- will not get true density
m <- ggplot(movies, aes(x=rating, weight=votes/sum(votes))) m + geom_histogram(aes(y=..density..)) + geom_density(fill=NA, colour="black")stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
library(plyr) # to access round_any movies$decade <- round_any(movies$year, 10) m <- ggplot(movies, aes(x=rating, colour=decade, group=decade)) m + geom_density(fill=NA)
Warning message: sum(weights) != 1 -- will not get true density
stat_bin for the histogram