ggplot 中的特殊变量(..count..、..density.. 等) [英] Special variables in ggplot (..count.., ..density.., etc.)
问题描述
考虑以下几行.
p <- ggplot(mpg, aes(x=factor(cyl), y=..count..))
p + geom_histogram()
p + stat_summary(fun.y=identity, geom='bar')
理论上,最后两个应该产生相同的情节.在实践中,stat_summary
失败并抱怨缺少所需的 y 美学.
In theory, the last two should produce the same plot. In practice, stat_summary
fails and complains that the required y aesthetic is missing.
为什么我不能在 stat_summary
中使用 ..count..
?我在文档中找不到任何关于如何使用这些变量的信息.
Why can't I use ..count..
in stat_summary
? I can't find anywhere in the docs information about how to use these variables.
推荐答案
扩展@joran 的评论,ggplot 中的特殊变量周围有双句点 (..count..
, ..密度..
等)由原始数据集的统计转换返回.那些特定的由 stat_bin
返回,它被 geom_histogram
隐式调用(注意在文档中 stat
参数的默认值是 "bin"
).您的第二个示例调用了一个不同的 stat 函数,该函数不会创建名为 ..count..
的变量.您可以使用
Expanding @joran's comment, the special variables in ggplot with double periods around them (..count..
, ..density..
, etc.) are returned by a stat transformation of the original data set. Those particular ones are returned by stat_bin
which is implicitly called by geom_histogram
(note in the documentation that the default value of the stat
argument is "bin"
). Your second example calls a different stat function which does not create a variable named ..count..
. You can get the same graph with
p + geom_bar(stat="bin")
在较新版本的 ggplot2
中,还可以使用 stat
函数代替封闭的 ..
,因此 aes(y = ..count..)
变成 aes(y = stat(count))
.
In newer versions of ggplot2
, one can also use the stat
function instead of the enclosing ..
, so aes(y = ..count..)
becomes aes(y = stat(count))
.
这篇关于ggplot 中的特殊变量(..count..、..density.. 等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!