微软Edx R数据科学MOOC中ggplot的..density..语法含义咨询
Understanding
..density.. in Your ggplot2 Code Great question—those double-dot wrapped variables can feel confusing at first, especially since they’re different from the ... parameter placeholders you’ve seen elsewhere. Let’s break this down clearly:
What Are ..variable.. Tokens?
- These are computed variables (sometimes called "stat variables") that ggplot2 generates internally when rendering statistical layers like histograms or density plots. The double dots are a deliberate syntax to distinguish them from columns in your original data frame.
- Unlike the
...used in function parameters (which act as a placeholder for variable-length arguments), these double-dot names refer to values calculated on-the-fly by ggplot’s statistical transformations.
What Does ..density.. Specifically Do?
- For
geom_histogram()(which usesstat_bin()under the hood),..density..represents the probability density of each bin. By default,geom_histogramuses..count..(the number of observations in each bin) for the y-axis. - Setting
y=..density..scales the histogram’s height so that the total area under the histogram equals 1. This matches the scale of the density curve created bygeom_density(), letting you overlay both elements on the same plot with aligned axes—critical for comparing the shape of your distribution.
Breaking Down Your Code
Looking at your plot definition:
p = ggplot(df, aes_string(col)) + geom_histogram(binwidth = bw, aes(y=..density..), alpha = 0.5) + geom_density(aes(y=..density..), color = 'blue') + geom_rug() + facet_grid(. ~ drive.wheels)
- The
geom_histogramusesy=..density..to swap from count-based height to density-based height. - The
geom_densityexplicitly usesy=..density..(though it defaults to this, writing it out makes your code more readable). - This alignment lets you easily compare how well the smooth density curve fits the binned histogram data, split by the
drive.wheelscategory viafacet_grid.
Finding Other Computed Variables
If you’re curious about other values you can access this way, check the documentation for the underlying stat function:
- For histograms, look at
?stat_bin—it lists variables like..count..,..freq..,..density.., and..width... - For density plots,
?stat_densitywill show its available computed variables.
内容的提问来源于stack exchange,提问作者user2193946
相关产品推荐
相关产品推荐

