Create a function in R to make all ggplot components more transparent

I am looking for a function that makes my ggplot graphs more transparent. Setting up a new theme I believe that this is not all good, because, as my own documents say, "Use theme () to change individual components of the theme, allowing you to control the appearance of all components without plot data . '

Suppose we have this simple graph:

ggplot(economics) +
  aes(unemploy, psavert) +
  geom_point() +
  geom_smooth(se = F) +
  ggtitle('Unemploy vs Personal Savings Rate')

It will look like this:

R ggplot2 graph: Unemploy vs Personal Savings Rate

My idea is to create a function that changes all the elements and makes them more transparent with some correlation, something like this:

make.invisible <- function(graph, alpha=.75){
  graph +
    # Change all elements
}

Is this possible with ggplot2?

+4
source share
2 answers

, . edit_colors() colorblindr. ( : .)

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)

enter image description here

alpha() , -, -. , , -, -:

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)

, , :

p2_alpha <- edit_colors(p2, scales::alpha, alpha = .7)

cowplot::plot_grid(p2_alpha, p2_mult_alpha)

enter image description here

( : alpha , : mult_alpha, ).

+2

,

print(p, vp=viewport(gp=gpar(alpha=0.3)))

enter image description here

+6

Source: https://habr.com/ru/post/1693186/


All Articles