I am looking for a function that makes my ggplot graphs more transparent. Customizing a new theme I thing that it´s not all good because as the own docs say, 'Use theme() to modify individual components of a theme, allowing you to control the appearance of all non-data components of the plot.'
Supose that we have this simple graph:
ggplot(economics) +
aes(unemploy, psavert) +
geom_point() +
geom_smooth(se = F) +
ggtitle('Unemploy vs Personal Savings Rate')
It will render like this:
My idea is to build a function that modifies all elements and makes them more transparency with some ratio, something like this:
make.invisible <- function(graph, alpha=.75){
graph +
# Change all elements
}
Is it possible with ggplot2?
Here is a solution following this post. It uses the edit_colors()
function from the colorblindr package. (Disclaimer: I'm an author of that package.)
p <- ggplot(economics) +
aes(unemploy, psavert) +
geom_point() +
geom_smooth(se = F) +
ggtitle('Unemploy vs Personal Savings Rate')
library(colorblindr) # devtools::install_github("clauswilke/colorblindr")
library(colorspace) # install.packages("colorspace", repos = "http://R-Forge.R-project.org") --- colorblindr requires the development version
# need also install cowplot; current version on CRAN is fine.
# modify alpha values using the alpha function from the scales package
p_alpha <- edit_colors(p, scales::alpha, alpha = .5)
# print
grid::grid.newpage()
grid::grid.draw(p_alpha)
One downside of the alpha()
function from scales is that it replaces the alpha value, it doesn't combine alpha values. So here is a simple example of how you can combine alpha values, using your own alpha combination function:
mult_alpha <- function(color, alpha = .5)
{
col <- grDevices::col2rgb(color, TRUE)/255
new_col <- grDevices::rgb(col[1, ], col[2, ], col[3, ], alpha*col[4, ])
new_col[is.na(color)] <- NA
new_col
}
p2 <- ggplot(iris, aes(Sepal.Length, fill = Species)) +
geom_density(alpha = .3) + theme_bw()
p2_mult_alpha <- edit_colors(p2, mult_alpha, alpha = .7)
Comparison between the two approaches shows that they give very different results for plots that already have some transparency:
p2_alpha <- edit_colors(p2, scales::alpha, alpha = .7)
cowplot::plot_grid(p2_alpha, p2_mult_alpha)
(left image: using alpha
from scales; right image: using mult_alpha
as defined above.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With