ggplot facetted geom_boxplot:减少x轴类别之间的空间

时间:2015-08-03 21:17:51

标签: r ggplot2 boxplot

我正在使用ggplot创建一个boxplot。当我减小箱图的宽度时,x轴类别之间的空间增加。我希望能够缩小x轴类别之间的空间,并使箱形图更接近彼此。

p<-ggplot(data.plot1, aes(time2, Count))
p+geom_boxplot(outlier.shape = NA, width=0.3)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  + 
  theme_bw()+  coord_cartesian(ylim = c(0, 850))+
  geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~CellType1)

enter image description here

所以,基本上,减少第0天,第30天,第100天之间的空间,并使箱形图彼此更接近。

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,缩小图形设备是实现这一目标的一种方式。在不改变图形设备大小的情况下,另一种方法是在条形图和面板两侧之间添加空格。 注意:由于您的问题无法重现,因此我使用了内置infert数据集,该数据集用于演示目的。假设这是你原来的并排方框图:

p<-ggplot(infert, aes(as.factor(education), stratum))
p+geom_boxplot(outlier.shape = NA, width=0.3)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  + 
  theme_bw()+  coord_cartesian(ylim = c(0, 80))+
  # geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~induced)

enter image description here

通过在每个面板的两端添加空格来将类别组合在一起:

p+geom_boxplot(outlier.shape = NA, width=0.6)+
  ggtitle("")+ylab("Cell Count (cells/mL) ")+ xlab("Time")  + 
  theme_bw()+  coord_cartesian(ylim = c(0, 80))+
  # geom_hline(data=normal1, aes(yintercept = val), linetype="dashed")+
  facet_grid(.~induced) +
  scale_x_discrete(expand=c(0.8,0))

enter image description here

scale_x_discrete(expand=c(0.8,0))中的两个数字表示“与轴隔开一定距离”的乘法和加法展开常数。见?scale_x_discrete。这有效地“拼凑”了每个面板中的箱形图,这也减少了每个箱形图的宽度。为了弥补这一点,我在width=0.6中将宽度增加到geom_boxplot。请注意,x轴标签现在重叠。您将不得不尝试不同的扩展因子和宽度大小,以获得您想要的结果。

另请参阅此问题以了解相关问题:Remove space between bars within a grid