R ggplot:如何将点与躲闪杆对齐?

时间:2018-06-01 20:12:00

标签: r ggplot2

我想知道如何将geom_point点与geom_bar躲避的条形位置对齐。

根据年份参数回避条形图,但无论年份参数如何,所有点都会在躲闪条形图的中间绘制。

enter image description here

可重复的代码:

set.seed(42)
dat <- data.frame(Response = rep(paste0("Response",1:4),2),
                  Proportion = round(runif(8),2),
                  Year = c(rep(2017,4),rep(2018,4)))
industries <- data.frame(Response = rep(paste0("Response",1:4),6),
                         Proportion = round(runif(24),2),
                         Year = rep(c(rep(2017,4),rep(2018,4)),3),
                         Cat = rep(paste0("Cat",1:3),c(rep(8,3))))
ggplot(dat, aes(Response, Proportion, label = paste0(Proportion*100,"%"), fill = factor(Year))) + 
  geom_bar(stat = "identity", position = "dodge" ) + 
  geom_point(data = industries, aes(Response, Proportion, fill = factor(Year), col= Cat), size = 3) +
  theme(axis.text.x = element_text(angle = 90)) + 
  scale_y_continuous(labels = scales::percent) + 
  geom_text(position = position_dodge(width = 1), angle = 90)

1 个答案:

答案 0 :(得分:3)

您需要group = factor(Year)中的aes(),然后是position = position_dodge(1)(由@Tung建议)。同样在x, y aes()中重复geom_point()也是多余的:

ggplot(dat, aes(Response, Proportion, label = paste0(Proportion*100,"%"), 
                fill = factor(Year))) + 
  geom_bar(stat = "identity", position = "dodge" ) + 
  geom_point(data = industries, aes(col= Cat, group = factor(Year)), size = 3,
             position = position_dodge(1)) +
  theme(axis.text.x = element_text(angle = 90)) + 
  scale_y_continuous(labels = scales::percent) + 
  geom_text(position = position_dodge(width = 1), angle = 90)

enter image description here