如何在同一分面网格图中绘制两个变量的多组并列箱线图
R ggplot2 使用预计算分位数绘制分面箱线图方案
你当前无法直接绘制箱线图的核心原因是:你的数据是已经提前计算好的分位数汇总结果,不是原始观测值,geom_boxplot()默认会自动对输入数据计算分位数,直接使用会得到错误结果,需要手动指定预计算的分位数映射。
步骤1:数据格式转换
首先将长格式的分位数数据转换为宽格式,让每个分位数对应单独的列:
library(tidyverse) synthese_wide <- synthese %>% pivot_wider(names_from = Quantile, values_from = Percentage)
步骤2:绘制分面箱线图
使用geom_boxplot(stat = "identity"),手动指定五个分位数的映射即可实现需求,分面规则和你原有逻辑保持一致:
# 定义分面标签 supp.labs <- c("A (%)", "B (°)", "C (m)") names(supp.labs) <- c("A", "B", "C") dose.labs <- c("输出1","输出2") names(dose.labs) <- c("Out1", "Out2") ggplot(synthese_wide, aes(x = Parameters_values)) + geom_boxplot( aes( ymin = Min, lower = Q1, middle = Med, upper = Q3, ymax = Max, fill = Treatement ), stat = "identity", position = position_dodge(width = 0.8), width = 0.7 ) + scale_y_continuous(name = "百分比") + scale_x_discrete(name = "模拟参数取值") + facet_grid( Output_var ~ Parameters, scales = "free", labeller = labeller(Output_var = dose.labs, Parameters = supp.labs) ) + guides(fill = guide_legend("处理组", title.position = "top")) + theme(legend.position = "bottom")
如果需要叠加原有分位数散点,可以在绘图代码中加入以下图层:
geom_point( data = synthese, aes(y = Percentage, colour = Quantile, shape = Treatement), position = position_dodge(width = 0.8) )
内容的提问来源于stack exchange,提问作者Meriem
相关产品推荐
相关产品推荐

