0
votes

i want a color scale like in the picture:

enter image description here

So from top to buttom we have:

a very bright yellow (white-ish), orange, red, black, blue, light blue to very bright blue (white-ish)

I want a value of 0 always to be displayed as "black". The smallest (negative) value should be that "extreme bright blue". The biggest value (postive) should be the "extreme bright yelllow".

Please note that the min and max are not equally distant from the origin 0.

Thats where i am:

library(ggplot2)
df <- data.frame(xDim = c(0, 1, 2, 0, 1, 2, 0, 1, 2), yDim = c(2, 2, 2, 1, 1, 1, 0, 0, 0), high = c(0, -1, 6, -3, 8, 5, -2, 7, 5))

ggplot(df, aes(xDim, yDim)) +
    geom_raster(aes(fill = high)) +
    scale_fill_gradient2(low = "blue", mid = "black", high = "red", midpoint = 0)
1
Use scale_fill_gradientn instead, with appropriate breaks and colors.Axeman
true that. is there a way to automate that? i have many DF with many different values.Andre Elrico
You could use quantile to set the breaks. Also consider the viridis color palettes: cran.r-project.org/web/packages/viridis/vignettes/… Some of the palettes seem similar to what you want, and would be a drop into ggplot with scale_fill_viridis(option="plasma").Eric Watt

1 Answers

1
votes

scale_fill_gradientn is most suited for this. You just need to get an appropriate vector of colors, then come up with a good range of values for those colors.

In your case, we could choose as colors:

col <- c('yellow', 'orange', 'red', 'black', 'blue', 'skyblue', 'white')

and as values:

val <- c(seq(min(df$high), 0, length.out = 4), seq(0, max(df$high), length.out = 4)[-1])

We need to use rescale according to the docs, so we do:

p <- ggplot(df, aes(xDim, yDim)) +
  geom_raster(aes(fill = high)) +
  scale_fill_gradientn(colours = col, values = scales::rescale(val))

cowplot::ggdraw() + cowplot::draw_plot(cowplot::get_legend(p))

enter image description here