簡體   English   中英

R ggplot:如何將點與躲閃桿對齊?

[英]R ggplot: How to align points with dodged bars?

我想知道如何將geom_point點與geom_bar躲避的條位置對齊。

根據Year參數躲避條形圖,但無論年份參數如何,所有點都在躲避條形圖的中間繪制。

在此輸入圖像描述

可重現的代碼:

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)

你需要aes() group = factor(Year) ,然后是position = position_dodge(1) (由@Tung建議)。 同樣在aes()geom_point()重復x, y是多余的:

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)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM