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

R语言使用ggplot2的facet_wrap功能实现多数据集分面箱线图对比

R语言分面箱线图实现方案

你可以先将宽格式的数据集转换为ggplot2适配的长格式,再按组别分面绘图即可,完整可运行代码如下:

library(tidyverse)
library(lubridate)

set.seed(129)

# 构造原始数据集
DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "month"),
                 O1 = runif(60,1,5), R1 = runif(60,1,5), C1 = runif(60,1,5),
                 O2 = runif(60,1,5), R2 = runif(60,1,5), C2 = runif(60,1,5),
                 O3 = runif(60,1,5), R3 = runif(60,1,5), C3 = runif(60,1,5))

# 转换为长表格式
DF_long <- DF %>%
  pivot_longer(cols = -Date,
               names_to = c("index_type", "group"),
               names_pattern = "^([A-Z])(\\d)$")

# 绘制分面箱线图
ggplot(DF_long, aes(x = index_type, y = value, fill = index_type)) +
  geom_boxplot(show.legend = FALSE) +
  facet_wrap(~group, nrow = 1) +
  labs(x = "指标类型", y = "数值") +
  theme_bw()

如果需要调整为更贴近参考的样式,可以修改主题参数:

ggplot(DF_long, aes(x = index_type, y = value, fill = index_type)) +
  geom_boxplot(show.legend = FALSE) +
  facet_wrap(~group, nrow = 1, 
             labeller = labeller(group = ~paste0("组别", .x))) +
  labs(x = NULL, y = "数值") +
  theme_bw() +
  theme(
    strip.background = element_rect(fill = "#e0e0e0"),
    strip.text = element_text(face = "bold")
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:54:03