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
相关产品推荐
相关产品推荐

