I would like to reproduce the attached plot on the training iris dataset with Petal.Length (x) and Sepal.Length (y). I assume it is about stat_density_2d arguments, but I was not able to reach the exact same picture. Any help is highly appreciated.
CodePudding user response:
You need to map alpha
to the calculated level
within stat_density2d_filled
, using alpha = after_stat(level)
inside aes
. Just tweak the breaks
argument to define where you want the contour cutoffs to be. I also found that adjusting the h
argument to set a slightly wider bandwidth than the default worked better than the default setting with this particular data set. Additionally, a call to scale_alpha_manual
will give you fine control over the opacity of each band - here I set a sequence of six values between 0 and 1, since only the first 5 will be used, meaning that the most dense bands still won't be fully opaque and "overpower" the points.
library(ggplot2)
ggplot(iris, aes(Petal.Length, Sepal.Length, fill = Species))
stat_density2d_filled(aes(alpha = after_stat(level)),
h = c(1, 1), breaks = c(0, 0.03, 0.1, 0.25, 0.5, 5))
geom_point(shape = 21, size = 3)
scale_alpha_manual(values = seq(0, 1, length = 6))
theme_minimal(base_size = 20)
coord_equal(expand = FALSE)
theme(legend.position = "none",
panel.border = element_rect(color = "gray80", fill = NA))