How to change the space between bars in geom_bar?

廉价感情. 提交于 2019-12-11 04:04:41

问题


I have a bar plot with positive values on both sides. When I changed the width of the bars, the space between them became to large and doesn't look good. I tried to manipulate this with position = position_dodge, but it doesn't work. How can I reduce the spaces between the bars?

Here is the code (originally posted here Stacked barplot crossing the x-axis) with my data:

Year <- factor(c("2003-2009","2003-2009","2003-2009","2003-2009","2003-2009","2009-2012",
              "2009-2012","2009-2012","2009-2012","2009-2012"))
Q <- c(.05,.25,.5,.75,.95)
Score <- c(6,6,4,3,1,23,20,19,24,32)
df <- data.frame(Year, Q, Score)

df <- transform(df, Score=ifelse(as.character(Year) %in% c("2003-2009"), -Score, Score))
df.split <- split(df, df$Score < 0)

ggplot() + 
  geom_bar(data=df.split[[1]],aes(x=Q, y=Score, fill=Year), stat="identity",width = 0.09)+
  geom_bar(data=df.split[[2]],aes(x=Q, y=Score, fill=Year), stat="identity",width = 0.09)+
  geom_hline(yintercept=0) +
  coord_flip()+
  scale_y_continuous(labels=abs,limits=c(-40,40))+ 
  theme_bw()+
  scale_x_continuous(breaks=c(.05,.25,.5,.75,.95))

回答1:


Treating the Q variable as a factor will set the space between the bars equal. Normally, when you reduce the width of the bars, the space between the bars increases. However, you want narrow bars and small spaces between the bars. You can achieve this by changing the height of the saved image.

The code (I also changed the width of the bars & the scale of the y-axis a bit):

ggplot() + 
  geom_bar(data=df.split[[1]],aes(x=as.factor(Q), y=Score, fill=Year), stat="identity", width = 0.4) +
  geom_bar(data=df.split[[2]],aes(x=as.factor(Q), y=Score, fill=Year), stat="identity", width = 0.4) +
  geom_hline(yintercept=0) +
  coord_flip() +
  scale_y_continuous(labels=abs,limits=c(-10,35)) + 
  theme_bw() +
  ggsave("myplot.png", width=8, height=2, dpi=300)

The result:

Note that I also deleted the scale_x_continuous(breaks=c(.05,.25,.5,.75,.95)) part of the plotting code as this will give an error when treating Q as a factor variable.



来源:https://stackoverflow.com/questions/22757401/how-to-change-the-space-between-bars-in-geom-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!