条形图中条形之间的特定空格 - ggplot2 - R.

Ale*_*ris 5 r ggplot2 geom-bar

我有一个简单的条形图,如下所示

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 现在,因为x轴的水平(翻转,现在看起来像是y)彼此有关系,例如男性和女性代表性别崩溃,工作和不工作代表另一个故障等,我希望轴之间留下一些空间每次细分以指出这些故障.

我已经尝试了一些东西scale_x_discrete和它的参数中断,但似乎这不是它的方式.有任何想法吗 ?

Sti*_*ibu 5

我不知道在条形图中设置不同距离的方法.但是,您可以添加高度为0且组之间没有标签的栏,如下所示:

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])
Run Code Online (Sandbox Code Playgroud)

一些评论:

  • a$x从一开始就是一个角色,所以没有必要打电话as.character给它.
  • 只有每个"空"栏都有不同的标签时,它才有效.这就是我选择三个不同字母的原因.
  • scale_x_discrete 用于抑制标签和刻度线.

结果如下: 在此输入图像描述