Overlay two ggplot2 stat_density2d plots with alpha channels

前端 未结 2 1730
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 03:19

I want to overlay two ggplot2 plots with alpha channels in a way that the resulting image shows both datasets. This is my test data:

data = read         


        
相关标签:
2条回答
  • 2020-12-01 03:31

    Here is exactly the same solution than @Roland, excepting that I suggest controur line. This allow you to appreciate the overlapping. I can't see how geom_tile and your idea of "multiplication" could enable you to appreciate that. Maybe if you use blue and red for none-overlapping area, and a "weighted" violet color for overlapping area. But I guess you would have to compute it in a previous step before ploting I guess.

    contour_line

    ggplot(rbind(data.frame(data, group="a"), data.frame(data2, group="b")), 
           aes(x=x,y=y)) + 
      stat_density2d(geom="density2d", aes(color = group,alpha=..level..),
                     size=2,
                     contour=TRUE) + 
      #scale_color_manual(values=c("a"="#FF0000", "b"="#00FF00")) +
      geom_point() +
      theme_minimal() +
      xlim(-3.3, 3.3) + ylim(-3.3, 3.3) +
      coord_cartesian(xlim = c(-3.2, 3.2), ylim = c(-3.2, 3.2))
    
    0 讨论(0)
  • 2020-12-01 03:51

    You should plot both densities on the same scale:

    ggplot(rbind(data.frame(data, group="a"), data.frame(data2, group="b")), 
           aes(x=x,y=y)) + 
      stat_density2d(geom="tile", aes(fill = group, alpha=..density..), 
                     contour=FALSE) + 
      scale_fill_manual(values=c("a"="#FF0000", "b"="#00FF00")) +
      geom_point() +
      theme_minimal() +
      xlim(-3.3, 3.3) + ylim(-3.3, 3.3) +
      coord_cartesian(xlim = c(-3.2, 3.2), ylim = c(-3.2, 3.2))
    

    enter image description here

    Otherwise you display a distorted picture of your data.

    0 讨论(0)
提交回复
热议问题