ggplot2道奇重叠 - 保留每个元素的宽度

时间:2017-08-17 07:12:19

标签: r ggplot2

希望它很容易理解。它与here基本相同。

enter image description here

使用

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
   geom_bar(position = position_dodge(preserve = "single"))

但我得到Error in position_dodge(preserve = "single") : unused argument (preserve = "single") /。 ggplot2版本2.2.1

那么如何修改代码

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
     geom_bar(position = "dodge")

不要像下面那样得到这个超宽的酒吧。 enter image description here

1 个答案:

答案 0 :(得分:4)

该论点已添加到开发版in january中的position_dodge。它还没有在CRAN上。

解决方法是计算ggplot2之外的统计信息:

ggplot(as.data.frame(with(mtcars, table(cyl = factor(cyl), vs = factor(vs)))), 
       aes(factor(cyl), y = Freq, fill = factor(vs))) +
  geom_col(position = "dodge") + 
  scale_fill_discrete(drop = FALSE)

resulting plot

这是有效的,因为零计数包含在传递给geom的数据中。