在 scale_fill_gradientn 中使用绝对值而不是相对值

Use absolute values not relative values in scale_fill_gradientn

我想要一个平滑的渐变,从 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)))

只需要设置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 日创建