ggplot2中的多个核心密度

时间:2017-11-23 19:09:19

标签: r ggplot2

我想将两种类型的数据的内核密度估计添加到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)

enter image description here

3 个答案:

答案 0 :(得分:2)

一种方法是使用两个stat_density_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)) 

enter image description here

答案 1 :(得分:2)

这可能会做你想要的: ```

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==1), geom = "raster", fill='blue',  aes(fill = ..density.., alpha = ..density..), contour = FALSE) +
  scale_alpha(range = c(0,0.8)) + 
  stat_density_2d(data = subset(mtcars, vs==0), geom = "raster", fill='red', aes(fill = ..density.., alpha = ..density..), contour = FALSE) +
  guides(alpha=FALSE)

```

Plot

答案 2 :(得分:1)

我在this post中发现的另一个可能的解决方案是在geom="tile"调用而不是stat_density2d()中使用geom="raster"

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 = "tile", aes(fill = factor(vs), alpha = ..density..), contour = FALSE, linetype=0) +
   scale_alpha(range = c(0,1))

enter image description here