如何修改ggplot2代码,使条形图彼此相邻而不是堆叠?

时间:2018-08-28 13:46:22

标签: r ggplot2 graph geom-bar

我在ggplot2中运行以下R代码。我需要调整代码,以使每个FY值的小节彼此相邻而不是堆叠。

我的代码如下:

 p1 <- ggplot(dff3, aes(x=Gender, fill=FY)) + ggtitle("Gender") + 
       xlab("Gender") +
       geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5) + 
       ylab("Percentage") + 
       coord_flip() + 
       theme_minimal() +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"))

 p1

情节看起来像这样: enter image description here像这样:

1 个答案:

答案 0 :(得分:1)

您可以在position_dodge()中使用geom_bar()。这是使用mtcars数据集的示例:

library(tidyverse)

ggplot(mtcars, aes(x=factor(am), fill=factor(vs))) + 
  ggtitle("Gender") + 
  xlab("Gender") +
  geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5, position = position_dodge()) + 
  ylab("Percentage") + 
  coord_flip() + 
  theme_minimal() +
  theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"))

enter image description here