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

如何为热图scale_fill_gradientn设置比例颜色刻度(0-1蓝,>1红)

比值数据的差异化配色解决方案

我需要为比值类数据(例如病例数/对照数)设置差异化配色规则:

  • 当比值处于0到1区间时(代表对照组数值更高),使用白色到蓝色的渐变
  • 当比值处于1到正无穷区间时(代表病例组数值更高),使用白色到红色的渐变

最初的绘图代码仅在所有比值都处于0-1范围时能正常工作,但当数据中存在大于1的比值,或者同时包含0-1和>1的混合数据时,红色区域无法正确显示,且我不能使用对数转换或归一化处理数值。


原改编代码(存在问题)

改编自Allan Cameron的代码尝试解决该问题,但存在显示异常:

mtcars2 <- mtcars
mtcars2$ratio1 <- mtcars$mpg / mtcars$disp
mtcars2$ratio2 <- mtcars$disp / mtcars$mpg
mtcars2$ratio3 <- mtcars$drat / mtcars$wt

a <- max(mtcars2$ratio1)

b <- ifelse(a < 2, 2, a) # 确保b是大于2的值,用于构建颜色尺度

ggplot(mtcars, aes(x = rownames(mtcars), y = 1, fill = mtcars2$ratio1)) +
  geom_tile() +
  theme_minimal() +
  scale_fill_gradientn(
    colours = c("blue", "white", "red"),
    na.value = "grey98",
    name = "ratio",
    values = c(0, 1, b)
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(
    size = 10, face = "bold", color = "black",
    angle = 45, hjust = 1
  )) # b必须始终大于1(这里选了2)

a <- max(mtcars2$ratio2)

b <- ifelse(a < 2, 2, a)

ggplot(mtcars, aes(x = rownames(mtcars), y = 1, fill = mtcars2$ratio2)) +
  geom_tile() +
  theme_minimal() +
  scale_fill_gradientn(
    colours = c("blue", "white", "red"),
    na.value = "grey98",
    name = "ratio",
    values = c(0, 1, b)
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(
    size = 10, face = "bold", color = "black",
    angle = 45, hjust = 1
  ))

a <- max(mtcars2$ratio3)

b <- ifelse(a < 2, 2, a)

ggplot(mtcars, aes(x = rownames(mtcars), y = 1, fill = mtcars2$ratio3)) +
  geom_tile() +
  theme_minimal() +
  scale_fill_gradientn(
    colours = c("blue", "white", "red"),
    na.value = "grey98",
    name = "ratio",
    values = c(0, 1, b)
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(
    size = 10, face = "bold", color = "black",
    angle = 45, hjust = 1
  ))

修正后的可运行代码

以下代码能够正确处理所有情况:

a = ifelse(max(mtcars2$ratio3) > 1, max(mtcars2$ratio3), 1)

b = ifelse(max(mtcars2$ratio3) > 1, 1/max(mtcars2$ratio3), 1)

c = ifelse(b == 1, 0.99, b)
           
ggplot(mtcars2, aes(x = rownames(mtcars), y = 1, fill = ratio3)) +
  geom_tile() +
  theme_minimal() +
  scale_fill_gradientn(
    colours = c("blue", "white", "red"),
    na.value = "grey98",
    name = "ratio",
    limits = c(0, a),
    values = c(0, c , 1)
  ) +
  theme_classic() +
  theme(axis.text.x = element_text(
    size = 10, face = "bold", color = "black",
    angle = 45, hjust = 1
  ))

内容的提问来源于stack exchange,提问作者Gabriel G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:45:36