如何在ggplot中按特定处理(如VIP)的升序排列箱线图
问题描述
希望将箱线图按照特定处理(例如VIP)的数值升序排列,目前X轴的Code是按字母顺序展示的,请问如何修改代码实现这个需求?
示例数据集
Peso <- structure(list(Accession = c("Potato", "Potato", "Potato", "Potato", "Potato", "Potato"), Genotype = c("#1", "#2", "#3", "#4", "#5", "#6"), Code = c("aa", "ab", "ac", "ad", "ae", "af"), Nome = c("L", "L", "L", "L", "L", "L"), Data = c("A", "A", "A", "A", "A", "A" ), Treatment = c("VIP", "VIP", "VIP", "MOCK", "MOCK", "MOCK"), Weight = c(1.9, 1.46, 1.52, 1.29, 1.05, 1.52)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))
现有绘图代码
Population <- ggplot(data = na.omit(Peso), aes(x = Code, y = Weight, fill = Treatment)) + geom_boxplot( alpha=0.2) + xlab("Genotype") + geom_point()+ ylim(0, 3.00) Population + ggtitle("21dpi Dry-Weight") + ylab("Weight (g)") + xlab("Genotype") + theme(plot.title = element_text(family = NULL, face = NULL, color = "black", size = 15)) + theme(axis.title.x = element_text(family = NULL, face = NULL, color = "black", 14)) + theme(axis.title.y = element_text(family = NULL, face = NULL, color = "black", 14)) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1, size = 9)) + scale_fill_manual(values=c("#33FF00", "#000000"))
解决方案
核心思路是将Code转换为有序因子,排序依据为VIP处理组内该Code对应的Weight统计值(均值/中位数均可),具体步骤如下:
- 提取VIP组数据,计算每个
Code的Weight均值(或中位数)并排序 - 将原数据中的
Code转换为按上述顺序排列的因子 - 基于转换后的因子绘图
修改后的完整代码:
library(dplyr) library(ggplot2) # 1. 生成VIP组Weight均值升序的Code顺序 vip_sorted_codes <- Peso %>% filter(Treatment == "VIP") %>% group_by(Code) %>% summarise(avg_weight = mean(Weight)) %>% arrange(avg_weight) %>% pull(Code) # 2. 将Code转为有序因子,指定排序规则 Peso$Code <- factor(Peso$Code, levels = vip_sorted_codes, ordered = TRUE) # 3. 绘制箱线图(X轴自动按因子顺序排列) Population <- ggplot(data = na.omit(Peso), aes(x = Code, y = Weight, fill = Treatment)) + geom_boxplot(alpha=0.2) + xlab("Genotype") + geom_point()+ ylim(0, 3.00) Population + ggtitle("21dpi Dry-Weight") + ylab("Weight (g)") + xlab("Genotype") + theme(plot.title = element_text(family = NULL, face = NULL, color = "black", size = 15)) + theme(axis.title.x = element_text(family = NULL, face = NULL, color = "black", size = 14)) + theme(axis.title.y = element_text(family = NULL, face = NULL, color = "black", size = 14)) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1, size = 9)) + scale_fill_manual(values=c("#33FF00", "#000000"))
补充说明
- 若需要用中位数排序,只需把
summarise(avg_weight = mean(Weight))替换为summarise(med_weight = median(Weight))即可 - 因子转换后,ggplot会自动遵循指定的
levels顺序绘制X轴,不再使用默认的字母排序
内容的提问来源于stack exchange,提问作者Luigi
相关产品推荐
相关产品推荐

