ggplot2 Error : Mapping a variable to y and also u

2019-07-17 04:08发布

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)

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?

Thank you very much for your help!!

2条回答
唯我独甜
2楼-- · 2019-07-17 04:31

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.

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))

enter image description here

Update: For a more thorough account of the error message, see this nice Q&A

查看更多
Bombasti
3楼-- · 2019-07-17 04:39

please refer to: Error with ggplot2 mapping variable to y and using stat="bin"

based on my experience, for ggplot2 version 0.92, there is only warnings for geom_bar() without default stat parameter. but for version 1.0.0, it will end with error. If you specify stat="identity" for bar plot using geom_bar.

查看更多
登录 后发表回答