I have the following snippet of code:
ggp <- ggplot()
...
scale_fill_continuous(high="#112A42", low="#4FA1E0", na.value="white")
...
that works. I would like to change the parameter low
in the previous function to be equal to the parameter high
reduced by some amount, for example 50%. Something like that:
ggp <- ggplot()
...
# Obviously it's wrong, but just to give you an idea of what I'm looking for
scale_fill_continuous(high="#112A42", low="#112A42"-50%, na.value="white")
...
Is there any way to do it?
CodePudding user response:
Not sure if you make your life a bit over complicated here, as perhaps you can just use any online color picker and select a nice "light blue" that suits you right and replace the current low for the one you want.
However if you want to calculate it for some reason, you can convert your high and low HEX values to RGB values and take the average of those RED, GREEN and REDS. Then convert that mid color, representing your "-50%" mid value color back from RGB to HEX. Then use the calculated mid as your value for low.
high <- "#112A42"
low <- "#4FA1E0"
rgb_mid <- (col2rgb(high) col2rgb(low)) / 2
mid <- rgb(rgb_mid[1], rgb_mid[2], rgb_mid[3], maxColorValue = 255)
mid
# [1] "#306591"
If you only want to define one value, the "high" you can calculate "a low", which means none of the R, G, B's can exceed 255. That ratio determines your lowest value. When you apply that to get the mean of the low and high, gives you also the 50% color based on just a high value..
high <- "#112A42"
rgb_low <- col2rgb(high) * 255 / max(col2rgb(high))
rgb_mid <- (col2rgb(high) rgb_low) / 2
mid <- rgb(rgb_mid[1], rgb_mid[2], rgb_mid[3], maxColorValue = 255)
mid
# [1] "#2966A0"
CodePudding user response:
You can lighten or darken arbitrary colors using colorspace::darken
and colorspace::lighten
. For example, let's define this little wrapper function:
library(ggplot2)
scale_fill_mygradient <- function(color = "gray", lighten = 0.5, ...) {
scale_fill_gradient(high = color,
low = colorspace::lighten(color, lighten),
...)
}
And a plot to test it on:
p <- ggplot(within(mtcars, car <- rownames(mtcars)),
aes(car, mpg, fill = disp))
geom_col()
theme_bw()
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
Now we can do
p scale_fill_mygradient("blue")
and
p scale_fill_mygradient("#112A42")
Created on 2022-07-20 by the reprex package (v2.0.1)