Specific spaces between bars in a barplot - ggplot2 - R

前端 未结 3 1110
北海茫月
北海茫月 2020-12-19 11:07

I have a simple bargraph like the following

a<-data.frame(x=c(\"total\",\"male\",\"female\",\"low education\",
            \"mid education\",\"high educ         


        
3条回答
  •  生来不讨喜
    2020-12-19 11:51

    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

提交回复
热议问题