简体   繁体   中英

multiple kernal densities in ggplot2

I would like to add a kernel density estimate for 2 types of data to a ggplot. If I use the following code, it displays a kernel density estimate for the 2nd factor level only. How do I get a kernel density estimate for both factor levels (preferably different colors)?

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)

在此处输入图片说明

One approach is to use two stat_density_2d layers with subsets of the data and manually color them. It is not exactly what you are after but with tweaking it can be solid:

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

在此处输入图片说明

This might do what you want : ```

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)

```

情节

Another potential solution that I discovered in this post is to use geom="tile" in the stat_density2d() call instead of 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))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM