position_dodge 根据填充位置不同工作方式不同
position_dodge works differently depending on location of fill
谁能解释一下为什么会这样?如果我在主调用中使用填充美学,我会得到我想要的结果。如果我在 geom_bar
的调用中使用它,我不会。我敢肯定一定有一个简单的原因,如果有人能启发我,我将不胜感激。
'Correct':
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))
position_dodge
需要 group
审美 "dodge on"。
fill
aesthetic
默默地创建了一个 group
aes
。
所以如果你把它放在主调用中 geom_text
将继承(隐藏的)group
aes。如果它放在 geom_bar
中,那么 geom_text
就没有 group
,所以它什么也不会闪避。
您可以通过在 geom_text
中添加一个 fill = year
来验证。这将发出有关 unknown aesthetic
的警告,但会 dodge
文本位置。
谁能解释一下为什么会这样?如果我在主调用中使用填充美学,我会得到我想要的结果。如果我在 geom_bar
的调用中使用它,我不会。我敢肯定一定有一个简单的原因,如果有人能启发我,我将不胜感激。
'Correct':
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))
position_dodge
需要 group
审美 "dodge on"。
fill
aesthetic
默默地创建了一个 group
aes
。
所以如果你把它放在主调用中 geom_text
将继承(隐藏的)group
aes。如果它放在 geom_bar
中,那么 geom_text
就没有 group
,所以它什么也不会闪避。
您可以通过在 geom_text
中添加一个 fill = year
来验证。这将发出有关 unknown aesthetic
的警告,但会 dodge
文本位置。