I need to adjust the midpoint location for a heatmap via ggplot2. I've googled around and have seen scale_fill_gradient2
be a great fit but the colors don't seem to match up to what I'm looking for. I know z needs a range from 0 to 1. Example dataset generation below:
library(ggplot2)
library(tibble)
library(RColorBrewer)
set.seed(5)
df <- as_tibble(expand.grid(x = -5:5, y = 0:5, z = NA))
df$z <- runif(length(df$z), min = 0, max = 1)
I tried plotting with the scale_fill_gradient2
but the blue color isn't coming as "dark" as I'd like.
ggplot(df, aes(x = x, y = y)) +
geom_tile(aes(fill = z)) +
scale_fill_gradient2(
low = 'red', mid = 'white', high = 'blue',
midpoint = 0.7, guide = 'colourbar', aesthetics = 'fill'
) +
scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) +
scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Therefore, I'm using scale_fill_distiller
with the color palette 'RdBu' which comes out with the color scale I need but the ranges and the midpoints aren't right.
ggplot(df, aes(x = x, y = y)) +
geom_tile(aes(fill = z)) +
scale_fill_distiller(palette = 'RdBu') +
scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) +
scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Is there a way to get the 2nd color scale but with the option to set midpoint range as the first?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…