2
votes

This is a bit of a long shot, but I was wondering if anyone ever tried to combine two different continuous gradient scales into one single scale (basically two different continuous functions into one single function) for a gradient fill in ggplot? Let me try to explain using an example:

x <- rep(1:10, each = 10)
y <- rep(1:10, 10)
fill <- sample(1:60, 100, replace = TRUE)

df_test <- as.data.frame(cbind(x, y, fill))

ggplot()+
  geom_tile(data = df_test, aes(x = x, y = y, fill = fill))+
  scale_fill_gradient2(low = "red",
                       mid = "white",
                       high = "blue",
                       midpoint = 30)

The code will generate a plot below, where the colors will diverge from 30 to the respective colors set for the high and the low values (blue and red in this case).

enter image description here

However, if for some reason, I want to set my midpoint to 50 rather than 30, the code and plot will look this:

ggplot()+
  geom_tile(data = df_test, aes(x = x, y = y, fill = fill))+
  scale_fill_gradient2(low = "red",
                       mid = "white",
                       high = "blue",
                       midpoint = 50)

enter image description here

As you can see here, even though I'm still specifying Blue as the color for the high point of my gradient, since my midpoint is now 50, the blue color is much more muted than before. It looks like scale_gradient2 just rescaled the color so that 0 is still red, but since midpoint is now 50, the high point color is a lighter blue.

My desired behavior is that the color I set for the high remains what it was in the first plot, and I realized I want to essentially combine two different scales together for a single gradient scale, where if the value is between 50 to 0, then it's a red gradient from white to red, then if the value is between 50 to 60, then it is a blue gradient from white to blue. I thought about adding a customized fill variable with my custom transformation, but that didn't really work out. Would anyone have a more elegant/working solution?

1
Don't know how to help, mayyybe this stackoverflow.com/questions/13888222/… canRicardo Semião e Castro

1 Answers

1
votes

Create your own color palette.

library(RColorBrewer)
reds=colorRampPalette(c("red", "white"))
blues=colorRampPalette(c("white", "blue"))

ggplot()+
  geom_tile(data = df_test, aes(x = x, y = y, fill = fill))+
  scale_fill_gradientn(colors=c(reds(50), blues(10)))

enter image description here