Hi. Could someone please show me how to have the alpha level for contour lines in stat_density_2d match the alpha for the corresponding area? I'm sure there is something obvious, I'm overlooking, so I apologize in advance.
Below, I would like to have the contour lines drawn around the geyser types to match the alpha setting. Thank you!
data(faithful)
# creating a categorical variable for color variation
faithful<-faithful %>%
mutate(geyser_types=cut(eruptions, c("1", "2", "3", "4", "5", "6"), c("A", "B", "C", "D", "E")))
# trying to plot densities, but with contour lines to match alpha setting
ggplot(data=faithful) +
stat_density_2d(aes(x=eruptions, y=waiting, color=geyser_types, fill=geyser_types), geom="polygon", bins=4, alpha=.1) +
geom_point(aes(x=eruptions, y=waiting, color=geyser_types))
I'm actually not sure why the alpha setting is applied only to the fill colors and not the line colors. However, one way around this is to use scale_colour_manual to manually set the colors for the colour aesthetic to be partially transparent.
In the code below, we set the alpha level to be 0.3 in scale_colour_manual which is then applied to the line colors. For the points, we override the alpha setting by including an alpha value in geom_point.
# Get number of color we'll need
n = length(unique(faithful$geyser_types))
ggplot(data=faithful,
aes(x=eruptions, y=waiting, color=geyser_types, fill=geyser_types)) +
stat_density_2d(geom="polygon", bins=4, alpha=0.1) +
geom_point(alpha=0.5, size=1) +
scale_colour_manual(values=hcl(seq(15,375,length=n+1)[1:n], 100, 65, alpha=0.3)) +
theme_classic()