如何按指定表型分组并按频率高低重新排序条形图
解决按指定表型顺序+基因型频率降序绘制条形图的问题
问题核心
你的代码未达到预期效果的原因是:仅调整了Phenotype的因子顺序,但x轴的Genotype未按「指定表型分组+组内频率降序」的规则设置为有序因子,导致条形图的排序不符合要求。
修改后的完整代码
library(tidyverse) library(ggpubr) # 示例数据集 df1 <- data.frame(Sample = c("PT1", "PT2", "PT3", "PT4", "PT5", "PT6", "PT7", "PT8", "PT9", "PT10"), Genotype = c("AA/BB", "AA/CC", "BB/CC", "AA/DD", "AA/AA", "BB/CC", "BB/DD", "CC/DD", "BB/BB", "AA/DD"), Phenotype = c("Red", "Blue", "Pink", "Blue", "Blue", "Pink", "Pink", "White", "Red", "Blue")) # 数据预处理:统计频率+设置有序因子 df2 <- df1 %>% select(Genotype, Phenotype) %>% # 统计每个基因型-表型组合的频率 count(Phenotype, Genotype, name = "Freq") %>% filter(Freq > 0) %>% # 先按指定表型顺序排序,再在每个表型内按频率降序排序 arrange(factor(Phenotype, levels = c("Blue", "Red", "Pink", "White")), desc(Freq)) %>% # 将Genotype转换为有序因子,顺序沿用arrange后的结果 mutate(Genotype = fct_inorder(Genotype), # 设置Phenotype的因子顺序,保证填充色与分组对应 Phenotype = fct_relevel(Phenotype, c("Blue", "Red", "Pink", "White"))) # 绘制条形图 ggplot(df2, aes(x = str_wrap(Genotype, 5), y = Freq, fill = Phenotype)) + geom_bar(stat = "identity", position = "dodge", color = "black") + theme_pubr() + theme(axis.text.x = element_text(angle = 270, vjust = 1, hjust = 1, size = 7), axis.text.y = element_text(size = 8)) + xlab("Genotypes by order of phenotype and freq") + scale_fill_manual(values = c("blue", "red", "pink", "white"))
关键修改说明
- 替换频率统计方式:用
count()替代table()+转置的操作,更符合tidyverse语法逻辑,避免数据结构转换带来的混乱。 - 设置基因型的有序顺序:通过
arrange()先按指定表型顺序排序,再在每个表型组内按频率降序排列,最后用fct_inorder()将Genotype转换为有序因子,确保x轴条形的排列顺序符合预期。 - 保留表型的因子顺序:确保填充颜色与指定的表型顺序一一对应,避免颜色错位。
内容的提问来源于stack exchange,提问作者vanish007
相关产品推荐
相关产品推荐

