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

ggplot箱线图无法生成箱体问题求助(统计作业场景)

箱线图无法生成箱体的问题排查与解决

我在完成统计作业时需要绘制箱线图,代码能正常运行,但就是出不来箱体。已经把Improvement字段转成数值型,也试过清空环境重新导入数据,问题还是没解决。

我的代码

train.df.improve %>% 
  ggplot(aes(x="", y= Improvement)) + 
  geom_boxplot() +
  ggtitle("Boxplot of Improvement in Squat Weight") + 
  xlab("") + 
  ylab("Improvement in Squat Weight (Kg)") + 
  coord_flip()

数据结构

structure(list(ID = 1:18, VO2.max_Pre = c(66.4, 70.9, 64.9, 68.6, 
76.7, 75.6, 78.1, 73.1, 74.4, 64.9, 63, 66.6, 64.2, 58.7, 66.4, 
61.9, 62.8, 60.6), VO2.max_Post = c(67.8, 81.7, 70.1, 73, 84.5, 
78.4, 80.5, 76, 78.7, 72.8, 67.3, 71.8, 70.1, 65, 72.4, 66.2, 
69, 64.5), Squat_Pre = c(120L, 120L, 130L, 130L, 110L, 130L, 
140L, 120L, 140L, 100L, 140L, 130L, 150L, 140L, 130L, 160L, 150L, 
100L), Squat_Post = c(140L, 150L, 160L, 160L, 140L, 160L, 170L, 
140L, 170L, 130L, 180L, 170L, 170L, 170L, 150L, 190L, 190L, 130L
), Improvement = c(20L, 30L, 30L, 30L, 30L, 30L, 30L, 20L, 30L, 
30L, 40L, 40L, 20L, 30L, 20L, 30L, 40L, 30L)), row.names = c(NA, 
-18L), class = "data.frame")

问题原因

代码里x=""会让ggplot把所有数据归为同一个分组,但coord_flip()翻转坐标后,箱体被压缩成了一条线,看起来像是没有生成箱体。

解决方案

有两种可行的解决方式:

  • 方式1:去掉坐标翻转,绘制垂直箱线图
train.df.improve %>% 
  ggplot(aes(x="", y= Improvement)) + 
  geom_boxplot() +
  ggtitle("Boxplot of Improvement in Squat Weight") + 
  xlab("") + 
  ylab("Improvement in Squat Weight (Kg)")
  • 方式2:保留水平箱线图,用虚拟因子变量替代空字符串
train.df.improve %>% 
  ggplot(aes(x=factor(1), y= Improvement)) + 
  geom_boxplot() +
  ggtitle("Boxplot of Improvement in Squat Weight") + 
  xlab("") + 
  ylab("Improvement in Squat Weight (Kg)") + 
  coord_flip() +
  scale_x_discrete(breaks=NULL) # 隐藏多余的x轴刻度

内容的提问来源于stack exchange,提问作者AlexValentine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:45:37