r - ggplot 分面 geom_boxplot : reduce space between x-axis categories

标签 r ggplot2 boxplot

我正在使用 ggplot 创建一个箱线图。当我减少箱线图的宽度时,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 天之间的空间并使箱线图彼此更接近。

最佳答案

正如评论中提到的,缩小图形设备是一种方法。在不改变图形设备大小的情况下执行此操作的另一种方法是在条形和面板侧面之间添加空间。 注:由于您的问题不可重现,我使用了内置 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.6geom_boxplot .请注意,x 轴标签现在重叠了。您将不得不尝试不同的扩展系数和宽度大小,以准确获得您想要的效果。

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

关于r - ggplot 分面 geom_boxplot : reduce space between x-axis categories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31796914/

相关文章:

r - 如何在R中查找附加数据集列表?

r - geom_tile 图的可变大小

r - 在 ggplot2 中绘制每个级别的平均值

r - 如何将此 ggplot2 条形图转换为线图?

r - 向多个箱线图添加点

r - 如何过滤掉特定列全部为na的位置

R 获取 AUC 并同时绘制多条 ROC 曲线

r - 使用 ggplot2 的表格箱线图

r - 如何仅在第一个数字上分割字符串

r - Boxplot 上的全文标签,添加了平均点