How to change the space between bars in geom_bar?

2019-07-16 16:34发布

问题:

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.