geom_boxplot:分面及分组内按中位数降序重排箱线图
当然可以实现这个需求,核心思路是先计算各分组的中位数,再将type转换为按中位数降序排列的有序因子,让ggplot按照这个自定义顺序绘制箱线图。
完整代码如下:
# 加载所需工具包 library(dplyr) library(forcats) library(ggplot2) # 生成示例数据 random_data = data.frame("name" = rep(c("A", "B"), each = 500), "nodes" = rep(c("X", "Y"), times = 500), "type" = rep(c("I", "II", "III", "IV"), times = 10, each = 25), "value" = rnorm(1000)) # 计算每个(name, nodes, type)组合的中位数 median_df <- random_data %>% group_by(name, nodes, type) %>% summarise(median_val = median(value), .groups = "drop") # 合并中位数数据,生成按中位数降序排序的有序type因子 sorted_data <- random_data %>% left_join(median_df, by = c("name", "nodes", "type")) %>% group_by(name, nodes) %>% mutate(type_sorted = fct_reorder(type, -median_val)) %>% # 负号实现降序排列 ungroup() # 绘制排序后的箱线图 ggplot(sorted_data, aes(y = nodes, fill = type_sorted, x = value)) + geom_boxplot(alpha = 1) + facet_wrap(~name) + labs(fill = "type") + # 将图例名称恢复为原名称 theme_bw()
关键步骤说明:
- 用
dplyr分组计算每个name-nodes-type组合的中位数; - 将中位数合并回原数据集后,在
name和nodes的分组内,用forcats的fct_reorder把type转换成按中位数降序排列的有序因子; - 绘图时使用这个有序因子作为填充变量,ggplot就会自动按设定顺序排列每个
nodes组内的箱线图。
内容的提问来源于stack exchange,提问作者thesecond
相关产品推荐
相关产品推荐

