How to change the space between bars in geom_bar?
Asked Answered
C

1

2

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))
Calesta answered 31/3, 2014 at 8:56 Comment(0)
W
2

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:

enter image description here

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.

Wyon answered 31/3, 2014 at 9:37 Comment(3)
Thank you for suggestions, but I've been wondering how to decrease spaces without changing the width of the bars.Calesta
If I understand you correctly, you want narrow bars and small spaces between the bars. I updated my answer. Does this give you the desired result?Wyon
Thank you. I've also experimented with "scale_x_discrete (expand = C (0,1.5))" at the end of the code. It also reduce spaces between the bars, but left too much below the lowest and above the highest bar.Calesta

© 2022 - 2024 — McMap. All rights reserved.