How do I create a continuous density heatmap of 2D scatter data in R?

后端 未结 3 1352
孤街浪徒
孤街浪徒 2020-12-13 10:12

I can generate a density plot of 1D data with:

qplot(mydatapoints, geom=\'density\')

I\'ve also seen plenty of examples of heatmap grids, b

3条回答
  •  温柔的废话
    2020-12-13 10:43

    I think you want a 2D density estimate, which is implemented by kde2d in the MASS package.

    df <- data.frame(x=rnorm(10000),y=rnorm(10000))
    

    via MASS and base R:

    k <- with(df,MASS:::kde2d(x,y))
    filled.contour(k)
    

    via ggplot (geom_density2d() calls kde2d())

    library(ggplot2)
    ggplot(df,aes(x=x,y=y))+geom_density2d()
    

    I find filled.contour more attractive, but it's a big pain to work with if you want to modify anything because it uses layout and takes over the page layout. Building on Brian Diggs's answer, which fills in colours between the contours: here's the equivalent with different alpha levels, with transparent points added for comparison.

    ggplot(df,aes(x=x,y=y))+
      stat_density2d(aes(alpha=..level..), geom="polygon") +
      scale_alpha_continuous(limits=c(0,0.2),breaks=seq(0,0.2,by=0.025))+
      geom_point(colour="red",alpha=0.02)+
      theme_bw()
    

    enter image description here

提交回复
热议问题