I have ggplot
with manual color scale by specify midpoint = 2.5
as below;
#create dataframe
df <-data.frame(x = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)), # create random data
y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)),
z = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)))
#plot
gg <-ggplot(df, aes(x=x, y=y, color=z)) +
geom_point() +
scale_color_gradient2(midpoint=2.5, low="red", mid="white",high="blue", space ="Lab")
, which results in following figure;
Here, I would like to set more vivid (or deep) red color (ie #FF0000 or rgb(255,0,0)) at the minimum edge of the color scale (iemin z value is min(df$z)[1] -3.718939
).
In this case, I do not want to move midpoint = 2.5
.
Do you have any solution?
I want to keep blue vivid color at the z maximum as in the original figure. I have noticed the existence of trans =
in scale_color_gradient2
thanks to the first answer. But, I have no idea how to solve my question.
Considering your sample, the mid point splits the data by 25% and 75% approximately.
Instead of having scale_color_gradient2 with three color calls, we can have scale_color_gradientn with four color calls and white as the second color (as the mid pint is just above 25%.
gg <-ggplot(df, aes(x=x, y=y, color=z)) +
geom_point() +
scale_color_gradientn(colors=c("red","white", "blue", "darkblue"), space ="Lab")
PS: You can also try colors=c("red","white", "lightblue", "blue")
Your gradient is already set with #FF0000
as the minimum. The scale is linear, so there's no getting around that.
Instead, you can consider transforming your color scale with trans=
in the scale_color_gradient2
call.
The defaults are log
, log2
and sqrt
. None of these are terribly helpful due to having negative values for z
.
You could instead set up a custom tranformation function with scales
:
library(ggplot2)
library(scales)
asinh_trans <- scales::trans_new("asinh_trans",
transform=function(x) asinh(x),
inverse=function(x) sinh(x))
ggplot(df, aes(x=x, y=y, color=z)) +
geom_point() +
scale_color_gradient2(midpoint=asinh(2.5),
low="red",
mid="white",
high="blue",
trans=asinh_trans,
space ="Lab")
I'll agree that this doesn't look perfect, but you can easily set up any arbitrary transformation by setting your own trans_new
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.