Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding space between bars in ggplot2

Tags:

r

ggplot2

I'd like to add spaces between bars in ggplot2. This page offers one solution: http://www.streamreader.org/stats/questions/6204/how-to-increase-the-space-between-the-bars-in-a-bar-plot-in-ggplot2. Instead of using factor levels for the x-axis groupings, however, this solution creates a numeric sequence, x.seq, to manually place the bars and then scales them using the width() argument. width() doesn't work, however, when I use factor level groupings for the x-axis as in the example, below.

library(ggplot2)  Treatment <- rep(c('T','C'),each=2) Gender <- rep(c('M','F'),2) Response <- sample(1:100,4) df <- data.frame(Treatment, Gender, Response)  hist <- ggplot(df, aes(x=Gender, y=Response, fill=Treatment, stat="identity")) hist + geom_bar(position = "dodge") + scale_y_continuous(limits = c(0,      100), name = "")  

Does anyone know how to get the same effect as in the linked example, but while using factor level groupings?

like image 839
aaron Avatar asked May 22 '11 00:05

aaron


People also ask

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.

How do I increase the space between grouped bars in ggplot2?

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 reduce the space between bars in Ggplot?

Example 2: Decrease Width and Increase Space between Bars. When we want to Decrease the Width of Bars and Increase Space between Bars, we simply have to use the width parameter to the geom_bar() function. Here we set the value of the width parameter as 0.40.


1 Answers

Is this what you want?

hist + geom_bar(width=0.4, position = position_dodge(width=0.5)) 
  • width in geom_bar determines the width of the bar.
  • width in position_dodge determines the position of each bar.

Probably you can easily understand their behavior after you play with them for a while.

enter image description here

like image 74
kohske Avatar answered Oct 07 '22 18:10

kohske