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

如何修复ggnewscale使用过程中的Y轴顺序失控问题

解决ggnewscale多色渐变热图Y轴因子顺序失效问题

你为Treatment列设置了因子水平(顺序为Treatment_2、Control、Treatment_1),但调用new_scale("fill")后Y轴顺序未按设定生效,核心问题出在过滤数据时引用了原始未处理的数据集:

在geom_tile的data = ~ filter(.x, df1$Treatment == "xxx")中,df1$Treatment调用的是最初未因子化的原始数据,而非管道中经过mutate处理后的因子化数据,导致ggplot无法识别你设定的Y轴顺序。

修正方法

把过滤条件里的df1$Treatment替换为.x$Treatment(.x代表管道传递的处理后数据集),或者直接使用列名Treatment(filter上下文默认引用当前数据框的列)。

修正后的完整代码

library(dplyr)   
library(tidyverse)
library(ggnewscale)

df1<- data.frame(Group = c("A","A","A","B","B","B","C","C","C"),
                  Treatment = c("Control", "Treatment_1", "Treatment_2", "Control", 
                                "Treatment_1","Treatment_2","Control", 
                                "Treatment_1","Treatment_2"),
                  Score = c(12,3,7,4,6,11,2,0,5))
                 
 df1 %>%
   mutate(Score = as.numeric(Score),
          Treatment = factor(Treatment, level = c("Treatment_2", "Control", "Treatment_1" )))%>%
   
 ggplot(mapping = aes( x = Group , y = Treatment)) +
   # 改用.x$Treatment引用处理后的因子列
   geom_tile(data = ~ filter(.x, .x$Treatment == "Treatment_1"), mapping = aes(fill = Score)) +
   scale_fill_gradientn(colors = hcl.colors(10, "YlOrBr"), guide = "colourbar") +
   
   new_scale("fill") +
   
   geom_tile(data = ~ filter(.x, Treatment == "Treatment_2"), mapping = aes(fill = Score)) +
   scale_fill_gradientn(colors = rev(hcl.colors(10, "Blues 3")), guide = "colourbar") +
   new_scale("fill") +
   
   geom_tile(data = ~ filter(.x, Treatment == "Control"), mapping = aes(fill = Score)) +
   scale_fill_gradientn(colors = hcl.colors(10, "YlGn"), guide = "colourbar") 

这样修改后,ggplot会识别你设定的因子水平,Y轴会按照Treatment_2、Control、Treatment_1的顺序显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:25:17