how to set alpha for contour lines in stat_density_2d

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!

# 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))

       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)) +


1 Like

Thank you for the workaround in scale_colour_manual():

 scale_colour_manual(values=hcl(seq(15,375,length=n+1)[1:n], 100, 100, alpha=0.1)) 

It works perfectly!

If your question's been answered (even if by you), would you mind choosing a solution? (See FAQ below for how).

Having questions checked as resolved makes it a bit easier to navigate the site visually and see which threads still need help.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.