ggplot2错误:将变量映射到y,并且还使用stat ="bin". “用于数据分析的典雅图形"中的示例 [英] ggplot2 Error : Mapping a variable to y and also using stat="bin". example from 'Elegant Graphics for Data Analysis'
问题描述
我正在尝试学习ggplot2
并将其应用于我自己的数据,但是在尝试从Hadley Wickham的数据分析的典雅图形"一书中复制图时遇到了一个问题(图4.10(右)) ,第4章:4.9.1结合几何和统计信息,第61页),使用以下代码:
I'm trying to learn ggplot2
to apply it to my own data, but have encountered a problem when trying to reproduce a plot from the book 'Elegant Graphics for Data Analysis' by Hadley Wickham (Fig 4.10 (right), chapter 4: 4.9.1 Combining geoms and stats, p. 61) using the following code:
d <- ggplot(diamonds, aes(carat)) + xlim(0, 3)
d + stat_bin(aes(y = 1, fill = ..count..), binwidth = 0.1, geom = "tile", position="identity")
它会导致以下错误消息:
It results in the following error message:
# Error : Mapping a variable to y and also using stat="bin".
# With stat="bin", it will attempt to set the y value to the count of cases in each group.
# This can result in unexpected behavior and will not be allowed in a future version of ggplot2.
# If you want y to represent counts of cases, use stat="bin" and don't map a variable to y.
# If you want y to represent values in the data, use stat="identity".
# See ?geom_bar for examples. (Defunct; last used in version 0.9.2)
如何重现所需的图/修复错误?如果可以的话,请您解释一下. geom_tile
如何产生相同类型的图?
How can I reproduce the desired plot/fix the error? Could you please explain it bit if possible. How could the same kind of plot be produced using geom_tile
?
非常感谢您的帮助!
推荐答案
在?geom_tile
中运行等效示例时,会产生相同的错误,例如cars + stat_bin(aes(fill=..count..), geom="tile", binwidth=3, position="identity")
.仍然在 此处 中找到了输出,还显示了什么我认为是ggplot2
版本中.
The same error is produced when running the equivalent examples in ?geom_tile
, e.g. cars + stat_bin(aes(fill=..count..), geom="tile", binwidth=3, position="identity")
. The output is still found here though, also showing what I assume was the warning message in older ggplot2
versions.
一种可能的解决方案是使用stat_bin2d
(带有虚拟y变量)并使用binwidth
自变量. binwidth
向量(c(0.1, 1)
)中的第一个数字是x值,第二个是y值. binwidth
未在帮助文本的参数"部分中记录,但可以在中找到示例
One possible solution would be to use stat_bin2d
, with a dummy y variable, and use the binwidth
argument. The first number in the binwidth
vector (c(0.1, 1)
) refers to x values and the second to the y values. binwidth
is not documented in the 'Arguments' section in the help text, but can be found among the examples
ggplot(diamonds, aes(x = carat, y = factor(1))) + xlim(0, 3) +
stat_bin2d(binwidth = c(0.1, 1))
Update: For a more thorough account of the error message, see this nice Q&A
这篇关于ggplot2错误:将变量映射到y,并且还使用stat ="bin". “用于数据分析的典雅图形"中的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!