Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use absolute values not relative values in scale_fill_gradientn

I would like a smooth gradient starting from red at 0 to white at 0.5 to green at 1.

My data doesn't cover this full range, and it seems scale_fill_gradientn takes the values argument to be relative to the data, rather than their actual values.

The plot produced below shows white above 0.5 rather than at 0.5. How can I correct this and set the gradient limits to the specific values I write, rather than relative to the data?

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)))

heatmap_example

like image 546
conor Avatar asked Feb 18 '20 23:02

conor


1 Answers

You just need to set the limits parameter of scale_fill_gradientn:

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))

Created on 2020-02-18 by the reprex package (v0.3.0)

like image 166
Allan Cameron Avatar answered Nov 15 '22 04:11

Allan Cameron