Hi,
I want to make one of the levels of my categorical let's say variable more transparent in order to see distribution underneath.
How do I do it ?
This code is not working properly, how to correct it ?
# Simulate some data
set.seed(123)
n <- 500
datasyn <- data.frame(
Some_results = rnorm(n),
Sex = sample(c("female", "male"), size = n, replace = TRUE)
)
# Load ggplot2 library
library(ggplot2)
# Create the plot
ggplot(datasyn, aes(x = Some_results, fill = Sex)) +
geom_density() +
scale_fill_manual(values = c("female" = "#FF0000", "male" = "#0000FF")) +
scale_alpha_manual(values = c("female" = 0.7, "male" = 0.2)) +
theme(legend.position = "bottom") +
labs(fill = "Sex")
This blue mountain completely obscuring a gray mountain which id situated behind. How to fix it, please ?
Additional thing is that legend is not completed, only male present.
Is it possible to change if possible as well, when density males are in the background and density females are in the foreground to reverse it in the plot and vice-versa ?
How to tweak a bit a legend, I mean how to increase squares and fonts in the legend ?
This is because changing the order of the colours just doesn't change the stacking order, female is still at the bottom, male on top. (Because they are drawn in alphabetic order female, then male)
With a high enough transparency (alpha <= 0.5) the effect shouldn't be so visible (okay the mixing is still a bit different).
What you can do is to reverse the stacking order using fct_rev() from the forcats package.
When you wnat to keep the alpha differentially you need to add the same for the alpha.
See also the settings for bigger legend.
For more control check this: Legend guide — guide_legend • ggplot2