I am trying to create a manual scale for the colors in one of my plots. My data span from 0 to 10, and I have quite a few very small numbers. Importantly I want two color gradients. One for points with values < 1, and one for points with values >= 1. Since I have quite a few very small numbers, I want to have the color gradient be on a log scale (diverging at 1).
Simulated data:
library(cowplot)
df <- data_frame(xs = rnorm(1000),
ys = rnorm(1000),
color_vals =c(runif(500, 0,.001), runif(500, .01,10)))
I know I can do this automatically like so (I know it doesn't make sense to have a white point, but this is just a toy example for my more complex map plot):
ggplot(df, aes(x=xs, y=ys, color=color_vals)) + geom_point() +
scale_color_gradient2(low="blue", high = "red", mid = "white", trans="log10")
I don't want this type of gradient though, because I want two increasing gradients, split at 1: (1) from grey to blue and (2) from yellow to red.
I know I can specify this with scale_color_gradientn
this way:
ggplot(df, aes(x=xs, y=ys, color=color_vals)) + geom_point() +
scale_color_gradientn(colors = c("grey", "blue", "yellow", "red"),
values = scales::rescale(c(0,1,1.000001, max(df$colors))))
but when I try to do this in tandem with the log transform, the gradient doesn't turn out correctly.
ggplot(df, aes(x=xs, y=ys, color=color_vals)) + geom_point() +
scale_color_gradientn(trans = "log10",
colors = c("grey", "blue", "yellow", "red"),
values = scales::rescale(c(0.000001,1,1.000001, max(df$colors))))
The closest I've gotten is to attempt to log-transform the numbers within rescale
, but that doesn't work properly (though it's close).
ggplot(df, aes(x=xs, y=ys, color=color_vals)) + geom_point() +
scale_color_gradientn(trans = "log10",
colors = c("grey", "blue", "yellow", "red"),
values = scales::rescale(log10(c(0.000001,1,1.000001, max(df$colors)))))
So how can I specify the correct values for my two gradients if I also want to the gradients to be log transformed?
min(df$colors)
as your starting point for the log10 scaling instead of .000001? – aosmithcolor_vals
? You only create acolors
variable in your data.frame. At the moment, I can not exactly reproduce your plots. – bVa