Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase the space between the bars in a bar plot in ggplot2?

Tags:

r

ggplot2

How can I increase the space between the bars in a bar plot in ggplot2 ?

like image 968
Jana Avatar asked Jan 13 '11 00:01

Jana


People also ask

How do I increase space between bars in bar chart?

To Increase or Decrease width of Bars of BarPlot, we simply assign one more width parameter to geom_bar() function.

How do I increase space between grouped bars in GGPlot2?

Grouped Bar Graph For grouped bars, there is no space between bars within each group by default. However, you can add some space between bars within a group, by making the width smaller and setting the value for position_dodge to be larger than width.

How do I add a space between bars in R?

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.


1 Answers

You can always play with the width parameter, as shown below:

df <- data.frame(x=factor(LETTERS[1:4]), y=sample(1:100, 4)) library(ggplot2) ggplot(data=df, aes(x=x, y=y, width=.5)) +    geom_bar(stat="identity", position="identity") +   opts(title="width = .5") + labs(x="", y="") +   theme_bw() 

Compare with the following other settings for width:

alt text

So far, so good. Now, suppose we have two factors. In case you would like to play with evenly spaced juxtaposed bars (like when using space together with beside=TRUE in barplot()), it's not so easy using geom_bar(position="dodge"): you can change bar width, but not add space in between adjacent bars (and I didn't find a convenient solution on Google). I ended up with something like that:

df <- data.frame(g=gl(2, 1, labels=letters[1:2]), y=sample(1:100, 4)) x.seq <- c(1,2,4,5) ggplot(data=transform(df, x=x.seq), aes(x=x, y=y, width=.85)) +   geom_bar(stat="identity", aes(fill=g)) + labs(x="", y="") +    scale_x_discrete(breaks = NA) +    geom_text(aes(x=c(sum(x.seq[1:2])/2, sum(x.seq[3:4])/2), y=0,                  label=c("X","Y")), vjust=1.2, size=8) 

The vector used for the $x$-axis is "injected" in the data.frame, so that so you change the outer spacing if you want, while width allows to control for inner spacing. Labels for the $x$-axis might be enhanced by using scale_x_discrete().

alt text

like image 154
chl Avatar answered Sep 21 '22 16:09

chl