You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot中stat_summary图形颜色与图例顺序不匹配的修复方法

解决ggplot图形颜色与图例顺序不匹配的问题

问题描述

我希望图形中的颜色顺序与图例保持一致。当前图例中绿色位于顶部,但在图形中它处于底部,该如何解决?

原代码

asv_for_graph_taxon %>%
  mutate(., presence=case_when(total_counts>0~'Present',
                               total_counts==0~'Absent',
                               .default = 'WTF'))%>%
  filter(., sampling_point_simple!='make_up_water')%>%
  mutate(., taxon = factor(taxon, levels = c('*Nevskia* (ASV0000002)', 
                                             'Unclassified *Hyphomicrobiales* (ASV0000011)',
                                             '*Methyloversatilis* (ASV0000013)',
                                             '*Methylobacterium* (ASV0000016)',
                                             'Unclassified *Bacteria* (ASV0000021)',
                                             'Unclassified *Hyphomicrobiaceae* (ASV0000036)',
                                             '*Acidovorax* (ASV0000046)',
                                             'Unclassified *Betaproteobacteria* (ASV0000072)',
                                             'Unclassified *Pseudomonadota* (ASV0000088)',
                                             '*Sphingobium* (ASV0000106)',
                                             '*Rubribacterium* (ASV0000107)',
                                             'Unclassified *Betaproteobacteria* (ASV0000127)',
                                             'Unclassified *Bacteria* (ASV0000171)',
                                             '*Novosphingobium* (ASV0000179)',
                                             '*Mesorhizobium* (ASV0000192)',
                                             '*Novosphingobium* (ASV0000193)',
                                             'Unclassified *Bacteria* (ASV0000214)',
                                             'Unclassified *Bacteria* (ASV0000277)',
                                             'Unclassified *Alphaproteobacteria* (ASV0000313)')))%>%
  filter(., asv%in%asvs_maaslin3_lp_logistic)%>%
  ggplot(., aes(x = lp_qpcr_2, y = presence, color = taxon))+
  stat_summary(fun.data = median_hilow, geom = 'pointrange', 
               fun.args = list(conf.int = 0.5),
               position = position_dodge(width = 0.8))+
  scale_color_manual(name = 'ASV',
                     values = as.vector(p21))+
  labs(x = 'Log(GU/L)',y='ASV Presence')+
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10))+
  theme_classic()+
  theme(text = element_text(size = 12, family = 'Times New Roman'),
        legend.key.size = unit(0.5, 'cm'), #change legend key size
        legend.key.height = unit(0.4, 'cm'), #change legend key height
        legend.key.width = unit(0.1, 'cm'), #change legend key width
        legend.spacing.x = unit(0.1, "cm"),
        legend.spacing.y = unit(0.1, "cm"),
        legend.position = 'right',
        legend.title = element_text(size = 9),
        legend.text = element_markdown(size = 9))

解决方案

问题核心是过滤后保留的taxon顺序与颜色向量p21的顺序不匹配,同时因子水平定义和实际显示的点顺序未对齐。按以下步骤修复:

1. 预处理数据并匹配颜色顺序

先单独完成数据过滤,提取实际保留的taxon水平,再从p21中对应提取颜色,确保颜色与taxon一一对应:

# 预处理并过滤数据
filtered_data <- asv_for_graph_taxon %>%
  mutate(presence = case_when(
    total_counts > 0 ~ 'Present',
    total_counts == 0 ~ 'Absent',
    .default = 'WTF'
  )) %>%
  filter(sampling_point_simple != 'make_up_water') %>%
  mutate(taxon = factor(taxon, levels = c(
    '*Nevskia* (ASV0000002)', 
    'Unclassified *Hyphomicrobiales* (ASV0000011)',
    '*Methyloversatilis* (ASV0000013)',
    '*Methylobacterium* (ASV0000016)',
    'Unclassified *Bacteria* (ASV0000021)',
    'Unclassified *Hyphomicrobiaceae* (ASV0000036)',
    '*Acidovorax* (ASV0000046)',
    'Unclassified *Betaproteobacteria* (ASV0000072)',
    'Unclassified *Pseudomonadota* (ASV0000088)',
    '*Sphingobium* (ASV0000106)',
    '*Rubribacterium* (ASV0000107)',
    'Unclassified *Betaproteobacteria* (ASV0000127)',
    'Unclassified *Bacteria* (ASV0000171)',
    '*Novosphingobium* (ASV0000179)',
    '*Mesorhizobium* (ASV0000192)',
    '*Novosphingobium* (ASV0000193)',
    'Unclassified *Bacteria* (ASV0000214)',
    'Unclassified *Bacteria* (ASV0000277)',
    'Unclassified *Alphaproteobacteria* (ASV0000313)'
  ))) %>%
  filter(asv %in% asvs_maaslin3_lp_logistic)

# 获取过滤后实际保留的taxon水平(按因子顺序)
retained_taxa <- levels(droplevels(filtered_data$taxon))
# 从p21中匹配对应顺序的颜色
matched_colors <- p21[match(retained_taxa, levels(filtered_data$taxon))]

2. 使用匹配后的颜色绘制图形

修改ggplot代码,用匹配好的颜色向量,确保图形颜色与图例顺序完全一致:

ggplot(filtered_data, aes(x = lp_qpcr_2, y = presence, color = taxon)) +
  stat_summary(
    fun.data = median_hilow, 
    geom = 'pointrange', 
    fun.args = list(conf.int = 0.5),
    position = position_dodge(width = 0.8)
  ) +
  scale_color_manual(name = 'ASV', values = matched_colors) +
  labs(x = 'Log(GU/L)', y = 'ASV Presence') +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
  theme_classic() +
  theme(
    text = element_text(size = 12, family = 'Times New Roman'),
    legend.key.size = unit(0.5, 'cm'),
    legend.key.height = unit(0.4, 'cm'),
    legend.key.width = unit(0.1, 'cm'),
    legend.spacing.x = unit(0.1, "cm"),
    legend.spacing.y = unit(0.1, "cm"),
    legend.position = 'right',
    legend.title = element_text(size = 9),
    legend.text = element_markdown(size = 9)
  )

3. 额外检查(若仍有问题)

如果图例与图形顺序还是不一致,可以添加guides(color = guide_legend(reverse = FALSE))强制图例顺序与因子水平一致;或者调整position_dodge的方向,确保点的排列顺序与图例对齐。


内容的提问来源于stack exchange,提问作者EllistonV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:15:54