position_dodge的工作方式取决于填充位置

时间:2017-07-12 13:25:57

标签: r ggplot2 geom-bar

任何人都可以解释为什么会这样吗?如果我在主要通话中使用填充美学,我会得到我想要的结果。如果我在调用geom_bar时使用它,我就不会。我确信必须有一个简单的理由,如果有人能够启发我,我将不胜感激。

'正确':

library(tidyverse)

df <- tibble(
  x = c("One", "Two", "Three", "One", "Two", "Three"),
  y = c(12, 10, 11, 10, 12, 11),
  year = c("2016", "2016", "2016", "2017", "2017", "2017")
)

ggplot(df, aes(x = x, y = y, fill = year)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_text(aes(label = y), position = position_dodge(.9))

结果:

其他方式:

ggplot(df, aes(x = x, y = y)) +
  geom_bar(stat = "identity", position = "dodge", aes(fill = year)) +
  geom_text(aes(label = y), position = position_dodge(.9))

1 个答案:

答案 0 :(得分:2)

position_dodge需要group美学来“躲闪”。 fill aesthetic默默地创建group aes

因此,如果您将其置于主要调用中geom_text将继承(隐藏)group aes。如果它被放入geom_bar,则geom_text没有group,因此它就没有任何内容。

您可以fill = yeargeom_text添加unknown aesthetic。这会发出关于dodge但会$product文字位置的警告。