如何在R中绘制含缺失分组级别的双因子箱线图
解决方法
1. 构造符合要求的数据框
先生成包含数值变量y、含缺失12月的month、双水平age(young/old)的数据集:
set.seed(123) # 设置随机种子保证结果可复现 data <- data.frame( y = rnorm(400), # 生成400个正态分布数值 month = sample(c(1:11,13:15), 400, replace = TRUE), age = sample(c("young", "old"), 400, replace = TRUE) )
2. 绘制包含缺失分组的箱线图
核心沿用之前的思路:将month转换为包含**所有目标级别(1-15)**的因子,同时通过*符号指定month和age的交互分组,这样就能展示所有月份(包括缺失的12月)与年龄组的组合箱线图,缺失的组会自动留空:
with(data, boxplot(y ~ factor(month, levels = 1:15) * age, xlab = "Month-Age Group", ylab = "Y Value", main = "Boxplot by Month and Age (Including Missing Month 12)"))
补充优化
如果觉得x轴标签过于拥挤,可添加las=2参数旋转标签:
with(data, boxplot(y ~ factor(month, levels = 1:15) * age, xlab = "Month-Age Group", ylab = "Y Value", main = "Boxplot by Month and Age (Including Missing Month 12)", las = 2))
内容的提问来源于stack exchange,提问作者Frans van der Slik
相关产品推荐
相关产品推荐

