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

如何用R语言base包boxplot()函数绘制四组动物身高箱线图

解决方法:用R基础boxplot()绘制多分组箱线图

先把你的数据集存入R的数据框:

df <- data.frame(
  animal = c(rep("sheep", 10), rep("goat", 8)),
  sex = c(rep("female", 5), rep("male", 5), rep("male", 5), rep("female", 3)),
  height = c(117, 115, 110, 95, 121, 106, 98, 119, 100, 121, 130, 125, 134, 112, 122, 129, 135, 139)
)

你原来的代码boxplot(height ~ animal)只按animal单一变量分组,要同时按动物种类+性别分组,有两种简单实现方式:

方法1:用公式交互项语法

直接在公式中使用animal * sex,表示同时考虑两个变量的组合分组:

boxplot(height ~ animal * sex, data = df, 
        main = "不同组动物身高箱线图",
        xlab = "动物-性别组",
        ylab = "身高",
        col = c("lightblue", "lightgreen", "pink", "orange"))

方法2:用interaction()生成组合分组变量

将animal和sex合并为一个新的分组变量,传入箱线图函数:

boxplot(height ~ interaction(animal, sex), data = df,
        main = "不同组动物身高箱线图",
        xlab = "动物-性别组",
        ylab = "身高",
        col = c("lightblue", "lightgreen", "pink", "orange"))

两种方法都会生成包含雌性绵羊、雄性绵羊、雌性山羊、雄性山羊四组的箱线图,你可以根据需求调整颜色、标题等可视化参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:42:39