filups21
filups21

Reputation: 1927

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)

enter image description here

Upvotes: 2

Views: 1097

Answers (3)

filups21
filups21

Reputation: 1927

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

enter image description here

Upvotes: 1

missuse
missuse

Reputation: 19716

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

enter image description here

Upvotes: 2

Joseph Budin
Joseph Budin

Reputation: 1360

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)

```

Plot

Upvotes: 2

Related Questions