如何在同一个ggplot中为scale_fill_gradient设置不同取值范围
在ggplot的scale_fill_gradient中设置不同取值限制的实现方法
嘿,这个需求很实用,我来给你两种常见的实现方案,看哪种更贴合你的场景~
1. 自定义全局颜色映射的取值范围
如果你只是想手动固定颜色标尺的最小/最大值(而不是默认使用数据中area列的全局极值),直接给scale_fill_gradient加上limits参数就可以了。比如你想让蓝色对应4,红色对应8,不管数据里的area实际是5-7.5,代码可以这么改:
library(ggplot2) # 生成数据 df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),roi=rep(1:10,10),area=runif(100, 5.0, 7.5)) df$time <- factor(df$time, levels=rev(levels(df$time))) # 修改后的绘图代码,自定义颜色映射范围 p1 <- ggplot(data=df, aes(x=factor(roi), y=time, fill = area)) + theme_minimal() + coord_fixed(ratio=1) + geom_tile(colour = "white", width = 1.0, height = 1) + # 手动设置取值限制,同时用oob参数处理超出范围的值 scale_fill_gradient(low="blue", high="red", limits = c(4, 8), oob = scales::squish) print(p1)
这里的limits = c(4, 8)就是强制把颜色映射的范围固定在4到8,oob = scales::squish会把超出这个范围的数值(比如如果数据里有高于8的area值)压缩到范围边界,避免出现缺失的颜色块。
2. 在同一个图中使用多组不同的颜色限制(多填充标尺)
如果你真的需要在同一个图里给不同的元素(比如某些ROI或者时间点)设置不同的颜色取值限制,那就要用到ggnewscale包来添加第二个独立的填充标尺。举个例子,比如我们把前5个ROI的颜色限制设为5-6,后5个设为6-7.5:
library(ggplot2) library(ggnewscale) # 生成数据 df=data.frame(time=as.factor(rep(0.5:9.5,each=10)),roi=rep(1:10,10),area=runif(100, 5.0, 7.5)) df$time <- factor(df$time, levels=rev(levels(df$time))) # 拆分数据为两组 df1 <- df[df$roi <=5,] df2 <- df[df$roi >5,] # 绘图:先画第一组,用第一组的颜色限制,然后添加新的填充标尺,再画第二组 p2 <- ggplot() + # 第一组:ROI1-5,颜色限制5-6 geom_tile(data=df1, aes(x=factor(roi), y=time, fill=area), colour="white", width=1.0, height=1) + scale_fill_gradient(low="lightblue", high="darkblue", limits=c(5,6), name="Area (5-6)") + # 添加新的填充标尺,让第二组的颜色映射独立生效 new_scale_fill() + # 第二组:ROI6-10,颜色限制6-7.5 geom_tile(data=df2, aes(x=factor(roi), y=time, fill=area), colour="white", width=1.0, height=1) + scale_fill_gradient(low="pink", high="darkred", limits=c(6,7.5), name="Area (6-7.5)") + theme_minimal() + coord_fixed(ratio=1) + labs(x="ROI", y="Time") print(p2)
这样图里就会出现两个独立的颜色标尺,分别对应两组数据的取值限制,完美实现同一个图里不同的填充范围设置~
内容的提问来源于stack exchange,提问作者Hoang Le
相关产品推荐
相关产品推荐

