Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific spaces between bars in a barplot - ggplot2 - R

I have a simple bargraph like the following

a<-data.frame(x=c("total","male","female","low education",
            "mid education","high education","working","not working"),
        y=c(80,30,50,20,40,20,65,35))
a$x<-as.character(a$x)
a$x<-factor(a$x,levels=unique(a$x))


ggplot(a,aes(x,y)) + 
geom_bar(stat="identity",fill="orange",width=0.4) +
coord_flip() +
theme_bw()

enter image description here Now , because the levels of the x axis (flipped and now seems like y ) have a relation with each other e.g male and female represent sex breakdown , working and not working represent another breakdown etc., I want the axis to leave some space between each breakdown in order to point out these breakdowns.

I have tried some things with scale_x_discrete and its parameter break but it seems that this is not the way it goes . Any ideas ?

like image 886
Alex Karvouniaris Avatar asked May 07 '15 12:05

Alex Karvouniaris


People also ask

How do I change the spacing between bars in ggplot2?

Set the width of geom_bar() to a small value to obtain narrower bars with more space between them. By default, the width of bars is 0.9 (90% of the resolution of the data). You can set this argument to a lower value to get bars that are narrower with more space between them.

How do I change the 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 you increase the space between bars in a bar plot in ggplot?

To make the bars narrower or wider, set the width of each bar with the width argument. Larger 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.


1 Answers

I don't know of a way to set different distances between bars in a barplot. However, you can add bars with height 0 and no label between the groups as follows:

a<-data.frame(x=c("total","a","male","female","b","low education",
                  "mid education","high education","c","working","not working"),
              y=c(80,0,30,50,0,20,40,20,0,65,35))
a$x<-factor(a$x,levels=unique(a$x))


ggplot(a,aes(x,y)) + 
   geom_bar(stat="identity",fill="orange",width=0.4) +
   coord_flip() +
   theme_bw() +
   scale_x_discrete(breaks=a$x[nchar(as.character(a$x))!=1])

Some remarks:

  • a$x is a character from the start, so there is no need to call as.character on it.
  • It only works, if the each "empty" bar has a different label. That's why I chose three different letters.
  • scale_x_discrete is used to suppress the labels and tick marks.

The result looks as follows: enter image description here

like image 184
Stibu Avatar answered Oct 04 '22 12:10

Stibu