我想将两种类型数据的核密度估计添加到 ggplot 中。如果我使用以下代码,它将仅显示第二个因子级别的核密度估计。如何获得两个因子水平(最好是不同颜色)的核密度估计?
ggplot(mtcars, aes(x = disp, y=mpg, color=factor(vs))) +
theme_bw() +
geom_point(size=.5) +
geom_smooth(method = 'loess', se = FALSE) +
stat_density_2d(geom = "raster", aes(fill = ..density.., alpha = ..density..), contour = FALSE) +
scale_alpha(range = c(0,1)) +
guides(alpha=FALSE)
最佳答案
一种方法是使用两个带有数据子集的 stat_密度_2d
图层并手动为它们着色。这并不完全是您想要的,但通过调整它可以是可靠的:
ggplot(mtcars, aes(x = disp, y=mpg, color=factor(vs))) +
theme_bw() +
geom_point(size=.5) +
geom_smooth(method = 'loess', se = FALSE) +
stat_density_2d(data = subset(mtcars, vs == 0), geom = "raster", aes(alpha = ..density..), fill = "#F8766D" , contour = FALSE) +
stat_density_2d(data = subset(mtcars, vs == 1), geom = "raster", aes(alpha = ..density..), fill = "#00BFC4" , contour = FALSE) +
scale_alpha(range = c(0, 1))
关于r - ggplot2 中的多个核密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47462068/