Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

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

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

qplot(mydatapoints, geom='density')

I've also seen plenty of examples of heatmap grids, but these are more akin to histograms for 1D data in that data goes into discrete buckets instead of showing a smooth curve.

Can I plot something similar to the 1D density but for 2D data, with (say) something like hue/saturation/lightness to represent the density?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...