6

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

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()

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

我已经尝试了一些事情,scale_x_discrete它的参数 break 但似乎这不是它的方式。有任何想法吗 ?

4

3 回答 3

8

我不知道如何在条形图中设置条形之间的不同距离。但是,您可以在组之间添加高度为 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])

一些备注:

  • a$x从一开始就是一个字符,所以不需要调用as.character它。
  • 仅当每个“空”条具有不同的标签时,它才有效。这就是为什么我选择了三个不同的字母。
  • scale_x_discrete用于抑制标签和刻度线。

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

于 2015-05-07T12:41:21.287 回答
2
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))

a$rel = c("a", "a", "a", "b", "b", "b", "c", "c") # set groups
ggplot(a, aes(rel, y, fill = factor(x))) + 
  geom_bar(stat = "identity", width = 0.5, position = position_dodge(0.7))
于 2015-05-07T12:30:06.837 回答
0

如果您指定 scale_x_discrete (或 y),您可以简单地添加一个“”,只要您希望空间出现在限制和标签语句中。这类似于第一个答案,但您不必向数据集添加零值。

例如,这个数据集只有 8 个条,但它们被分成两组,每组四个。

scale_x_discrete(limits=c("BMayC","UMayC","BMayN","UMayN","","BJuneC","UJuneC","BJuneN","UJuneN"), 标签=c("BMayC", "UMayC","BMayN","UMayN","","BJuneC","UJuneC","BJuneN","UJuneN"))

于 2016-05-04T14:14:00.623 回答