In the plot below, the range in a goes from 0.001 to 0.7 but the legend doesn't have the middle value in the cyan color. Is there a way I can force that the middle value in the range of a be in the middle of the colour scale?
a <- c(0.1, 0.05, 0.09, 0.001, 0.7, 0.002, 0.1, 0.015, 0.05, 0.013, 0.05, 0.0021, 0.05, 0.002, 0.5, 0.01, 0.2, 0.001)
b <- c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9)
depth <- seq(1:18)
df <- data.frame(a, b, depth)
colors <- c("darkblue", "blue", "cyan", "yellow", "red")
range(df$a)
> range(df$a)
[1] 0.001 0.700
ggplot(df, aes(x = b, y = depth, fill = a)) +
geom_tile(width = 1, height = 1) +
scale_y_reverse(name = "Depth (m)") +
scale_fill_gradientn(colors = colors, limits = c(0.01, 0.3), oob = scales::squish) +
labs(x = "Category", y = "Depth (m)", fill = "Value") +
theme_minimal()
When setting the scale limits manually ...
## ggplot code +
scale_fill_gradientn( ..., limits = c(.01, 0.3)))
... make sure they fit the range of the color-mapped data (here: c(.001, .7)
, or leave the manual specification altogether, in which case ggplot
takes care of it.
works:
## ggplot code +
scale_fill_gradientn(colors = colors,
limits = c(0.001, 0.07) # match value range or skip
oob = scales::squish
)