You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何缩小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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:45:49