如何缩小ggplot2生成的过宽箱线图宽度?
缩小ggplot箱线图宽度的几种方法
你的单变量箱线图过宽,是因为ggplot在未指定x轴分类时,默认分配了较宽的水平空间。可以通过以下几种方式调整:
方法1:添加占位x变量并限制轴范围
在aes中加入x=1作为占位分类,配合xlim压缩x轴范围,再微调箱线图自身宽度,让整体更紧凑:
ggplot(throu, aes(x=1, y=throughput_time)) + geom_boxplot(fill="slateblue", alpha=0.2, width=0.3) + xlab("")+ylab("案例持续天数")+ theme_classic()+ theme(axis.ticks.x = element_blank(), axis.text.x = element_blank()) + xlim(0.5, 1.5)
方法2:调整绘图宽高比
通过theme()的aspect.ratio参数设置宽高比例,数值越小,图的宽度相对高度越窄:
ggplot(throu, aes(y=throughput_time)) + geom_boxplot(fill="slateblue", alpha=0.2, width=0.5) + xlab("")+ylab("案例持续天数")+ theme_classic()+ theme(axis.ticks.x = element_blank(), axis.text.x = element_blank(), aspect.ratio = 0.3)
方法3:导出时精确指定尺寸
如果需要导出图片,直接用ggsave()设置宽度和高度参数,精准控制最终图的大小:
p <- ggplot(throu, aes(y=throughput_time)) + geom_boxplot(fill="slateblue", alpha=0.2, width=0.5) + xlab("")+ylab("案例持续天数")+ theme_classic()+ theme(axis.ticks.x = element_blank(), axis.text.x = element_blank()) ggsave("boxplot.png", p, width=4, height=6) # 可按需调整width和height的数值
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

