【R语言编程绘图-箱线图】

发布于:2025-05-28 ⋅ 阅读:(17) ⋅ 点赞:(0)

基本箱线图绘制

使用ggplot2绘制箱线图的核心函数是geom_boxplot()。以下是一个基础示例,展示如何用iris数据集绘制不同物种(Species)的萼片长度(Sepal.Length)分布:

library(ggplot2)
ggplot(iris, aes(x = Species, y = Sepal.Length)) + 
  geom_boxplot()

颜色与填充控制

通过fillcolor参数可分别控制箱线图内部填充色和边框颜色:

ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + 
  geom_boxplot(color = "black", alpha = 0.7)
  • alpha参数调整透明度(0-1)
  • 颜色支持Hex格式(如#FF5733)或R颜色名称

异常值样式调整

箱线图的异常值(outliers)可通过以下参数定制:

geom_boxplot(
  outlier.color = "red",       # 异常点颜色
  outlier.shape = 19,          # 点形状编号
  outlier.size = 3,            # 点大小
  outlier.alpha = 0.6          # 透明度
)

宽度与位置调整

width参数控制箱体宽度,position调整分组位置:

ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + 
  geom_boxplot(width = 0.5, position = position_dodge(0.8))

分组箱线图

当需要按两个分类变量分组时,使用交互变量或分面:

# 方法1:dodge分组
ggplot(mpg, aes(x = class, y = hwy, fill = factor(cyl))) + 
  geom_boxplot(position = position_dodge(preserve = "single"))

# 方法2:分面
ggplot(mpg, aes(x = class, y = hwy)) + 
  geom_boxplot() + 
  facet_wrap(~cyl)

统计信息显示

可通过stat_summary()叠加显示均值等统计量:

ggplot(iris, aes(x = Species, y = Sepal.Length)) + 
  geom_boxplot() +
  stat_summary(fun = mean, geom = "point", shape = 18, size = 3, color = "red")

水平箱线图

交换x/y映射即可创建水平箱线图:

ggplot(iris, aes(y = Species, x = Sepal.Length)) + 
  geom_boxplot()

在这里插入图片描述

完整参数列表

geom_boxplot()支持的完整美学参数(aesthetics)包括:

  • x:分类变量(必需)
  • y:连续变量(必需)
  • lower/upper:自定义箱体范围
  • middle:自定义中位数线
  • ymin/ymax:自定义须线范围
  • group:强制分组变量
  • weight:加权箱线图

主题定制

通过theme()函数可精细调整标题、坐标轴等元素:

ggplot(iris, aes(x = Species, y = Sepal.Length)) + 
  geom_boxplot() + 
  labs(title = "鸢尾花萼片长度分布") + 
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
# 加载必要的库
library(ggplot2)

# 创建示例数据
df <- data.frame(
  group = rep(c("A", "B", "C"), each = 100),
  value = c(rnorm(150, mean = 0), rnorm(60, mean = 1), rnorm(400, mean = 2))
)

# 绘制箱线图
p <- ggplot(df, aes(x = group, y = value)) +
  geom_boxplot(width = 0.6, fill = "white", color = "black") +  # 使用白色填充,黑色边框
  labs(title = "Boxplot of Values by Group",  # 标题
       x = "Group",  # X轴标签
       y = "Value") +  # Y轴标签
  theme_minimal() +  # 使用简洁主题
  theme(plot.title = element_text(size = 16, face = "bold", hjust = 0.5),  # 标题样式
        axis.title = element_text(size = 14, face = "bold"),  # 轴标题样式
        axis.text = element_text(size = 12),  # 轴刻度标签样式
        legend.position = "none",
        axis.line = element_line(color = "black")
        
        )  
# 显示图像
print(p)

# 保存为高分辨率图像
ggsave("boxplot.png", plot = p, width = 8, height = 6, dpi = 300)

在这里插入图片描述