【问题标题】:Use absolute values not relative values in scale_fill_gradientn在 scale_fill_gradientn 中使用绝对值而不是相对值
【发布时间】:2020-02-18 23:35:10
【问题描述】:

我想要一个平滑的渐变,从 0 处的红色到 0.5 处的白色到 1 处的绿色。

我的数据没有涵盖这个完整的范围,似乎scale_fill_gradientnvalues 参数与数据相关,而不是它们的实际值。

下图显示白色高于 0.5 而不是 0.5。如何更正此问题并将梯度限制设置为我写入的特定值,而不是相对于数据?

library(tidyverse)
set.seed(1)
expand_grid(x=1:10, y=1:10) %>%
  mutate(val = rnorm(100, mean = 0.55, sd = 0.05)) %>%
  ggplot(aes(x, y)) +
  geom_tile(aes(fill = val)) +
  geom_text(aes(label = round(val, 3))) + 
  scale_fill_gradientn(colours = c("red","white","green"),
                       values = scales::rescale(c(0.0, 0.5, 1.0)))

【问题讨论】:

    标签: r ggplot2 gradient heatmap


    【解决方案1】:

    只需要设置scale_fill_gradientnlimits参数即可:

    library(tidyverse)
    set.seed(1)
    expand_grid(x=1:10, y=1:10) %>%
      mutate(val = rnorm(100, mean = 0.55, sd = 0.05)) %>%
      ggplot(aes(x, y)) +
      geom_tile(aes(fill = val)) +
      geom_text(aes(label = round(val, 3))) + 
      scale_fill_gradientn(colours = c("red","white","green"),
                          limits = c(0.0, 1.0))
    

    reprex package (v0.3.0) 于 2020 年 2 月 18 日创建

    【讨论】:

    • 这适用于我的具体示例,中点为 0.5。一般情况呢?假设我想要 0.45 的白色?还是扩展到三种以上的颜色?
    • @conor 那是当你添加 rescale - 你使用限制 with 规模,而不是代替它。限制只是说明您要将最小和最大点设置为什么。重新缩放设置您希望更改发生的最小到最大范围。
    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 2016-11-14
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多