任何人都可以解释为什么会这样吗?如果我在主要通话中使用填充美学,我会得到我想要的结果。如果我在调用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))
答案 0 :(得分:2)
position_dodge
需要group
美学来“躲闪”。
fill
aesthetic
默默地创建group
aes
。
因此,如果您将其置于主要调用中geom_text
将继承(隐藏)group
aes。如果它被放入geom_bar
,则geom_text
没有group
,因此它就没有任何内容。
您可以fill = year
向geom_text
添加unknown aesthetic
。这会发出关于dodge
但会$product
文字位置的警告。