r - ggplot2 中的多个核密度

标签 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

最佳答案

一种方法是使用两个带有数据子集的 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)) 

enter image description here

关于r - ggplot2 中的多个核密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47462068/

相关文章:

r - 使用 R 从具有可见中断的大系列中提取迷你系列(绘制时)

r - 查找数据框对角线上的所有零

r - geom_errorbar 上为正均值,下为负均值

r - qplot ylab 中的下标和上标 [R]

r - 将日期和时间转换为日期+时间戳

重新排列混合输入数据框

r - 在 R Shiny 中的公共(public)服务器功能下根据先前的 selectInput 更新 selectInput

r - 如何绘制前 5 个正值和前 5 个负值

r - 按组划分的真/假值计数条形图(斜线图)

r - 在同一图表R上绘制两个图,ggplot2 par(mfrow())