Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase space between bars in ggplot

Tags:

r

ggplot2

I have a bar plot:

p <- ggplot(data=df, aes(x=Gene, y=FC, fill=expt, group=expt))
p <- p + geom_bar(colour="black", stat="identity", position = position_dodge(width = 0.9))
p <- p + geom_errorbar(aes(ymax = FC + se, ymin = FC, group=expt),
                position = position_dodge(width = 0.9), width = 0.25)
p

I want to increase the spacing between bars (for each bin). I've tried messing around with the position_dodge(width = ...) but it skews my error bars:

enter image description here

There are several other questions that relate to this:

  • This question has an answer that seems to do the trick (but difficult to implement)
  • When I use the answer to this question I get the following:

enter image description here

i.e it seems to increase the between bins, but at the expense of overlapping with the neighbouring bar

like image 831
fugu Avatar asked Jul 16 '15 15:07

fugu


People also ask

How do I increase space between bars in bar chart?

To set space between bars in Bar Plot drawn using barplot() function, pass the required spacing value for space parameter in the function call. space parameter is optional and can accept a single value or a vector to set different space between bars in the bar plot.

How do I widen a bar in R?

Adjusting Bar Width and SpacingLarger values make the bars wider, and smaller values make the bars narrower. To add space between bars, specify the space argument. The default value is 0.2.

How do I move bars closer together in R?

If you want the bars to touch set width = 1 . If you want them to almost touch use width = 0.9 .


1 Answers

You can adjust the width outside of the position_dodge as well (in geom_bar),

ggplot(data=df, aes(x=Gene, y=FC, fill=expt, group=expt)) +
  geom_bar(colour="black", stat="identity", position = position_dodge(width = 0.8), width=0.5) +
  geom_errorbar(aes(ymax = FC + se, ymin = FC, group=expt),
                position = position_dodge(width = 0.8), width = 0.25)

enter image description here

or

dodge <- position_dodge(width = 0.5)

ggplot(data=df, aes(x=Gene, y=FC, fill=expt, group=expt)) +
  geom_bar(colour="black", stat="identity", position=dodge, width=0.5) +
  geom_errorbar(aes(ymax = FC + se, ymin = FC, group=expt),
                position = dodge, width = 0.25)

enter image description here

like image 158
Rorschach Avatar answered Nov 15 '22 05:11

Rorschach