Reputation: 1927
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)
Upvotes: 2
Views: 1097
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))
Upvotes: 1
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))
Upvotes: 2
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)
```
Upvotes: 2