简体   繁体   中英

R ggplot: How to align points with dodged bars?

I'd like to know how to align geom_point points with the geom_bar dodged bars positions.

The bars are dodged according to the Year parameter but the points all plot in the middle of the dodged bars regardless of their Year parameter.

在此输入图像描述

Reproducible code:

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)

You'd need group = factor(Year) in aes() , then position = position_dodge(1) (as suggested by @Tung). Also repeating x, y in aes() for geom_point() is superfluous:

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)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM