How do I change the transparency of a group in ggpubr plots. example dataset
library(ggpubr)
# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)
head(df[, c("wt", "mpg", "cyl")], 3)
data is:
wt mpg cyl
<dbl> <dbl> <fct>
Mazda RX4 2.620 21.0 6
Mazda RX4 Wag 2.875 21.0 6
Datsun 710 2.320 22.8 4
I tried to create the plot with regression line using following code:
ggscatter(df, x = "wt", y = "mpg",
add = "reg.line", add.params = list(color = "white", fill = "blue"),
conf.int = TRUE, # Add confidence interval
cor.coef = TRUE, # Add correlation coefficient
cor.coeff.args = list(method = "pearson"),
color = "cyl", shape = "cyl",
palette = c("#FF0000", "#0000FF", "#00FF00"),
ellipse = TRUE
)
# ggsave('test.png', width=6, height=6, units="in", dpi=300)
It gave me an output as follows:
I want to make red color more transparent from this figure.
You can change the alpha by changing the ggplot object itself rather than changing the grobs after the plot is built. This keeps the legend consistent with the plot, and allows you to modify theme elements, scales etc
library(ggpubr)
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)
p <- ggscatter(df, x = "wt", y = "mpg",
add = "reg.line", add.params = list(color = "white", fill = "blue"),
conf.int = TRUE, # Add confidence interval
cor.coef = TRUE, # Add correlation coefficient
cor.coeff.args = list(method = "pearson"),
color = "cyl", shape = "cyl",
palette = c("#FF0000", "#0000FF", "#00FF00"),
ellipse = TRUE
)
p$layers[[3]]$aes_params <- list()
p$layers[[3]]$mapping <- aes(wt, mpg, color = cyl, fill = cyl, group = cyl,
alpha = cyl)
p <- p + scale_alpha_manual(values = c(0.02, 0.2, 0.2), name = "cyl")
p