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

后端 未结 3 1349
孤街浪徒
孤街浪徒 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:42

    Combining two other answers (one pointing to geom_density2d and one giving sample data and scale_colour_gradient):

    df <- data.frame(x=rnorm(10000),y=rnorm(10000))
    ggplot(df,aes(x=x,y=y))+
        stat_density2d(aes(fill=..level..), geom="polygon") +
        scale_fill_gradient(low="blue", high="green")
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-13 10:47

    There's also scale_colour_gradient()

    df <- data.frame(x=rnorm(10000),y=rnorm(10000))
    ggplot(df, aes(x,y,colour=y)) + geom_point() + scale_colour_gradient(low="blue",high="red")
    
    0 讨论(0)
提交回复
热议问题