[英]How do I create a continuous density heatmap of 2D scatter data in R?
I can generate a density plot of 1D data with:我可以生成密度 plot 的一维数据:
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?我可以 plot 类似于 1D 密度的东西,但对于 2D 数据,用(比如说)像色相/饱和度/亮度来表示密度吗?
I think you want a 2D density estimate, which is implemented by kde2d
in the MASS
package.我想你想要一个 2D 密度估计,它是由
MASS
kde2d
中的 kde2d 实现的。
df <- data.frame(x=rnorm(10000),y=rnorm(10000))
via MASS
and base R:通过
MASS
和基础 R:
k <- with(df,MASS:::kde2d(x,y))
filled.contour(k)
via ggplot
( geom_density2d()
calls kde2d()
)通过
ggplot
( geom_density2d()
调用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.我发现
filled.contour
更有吸引力,但如果你想修改任何东西,使用它会很痛苦,因为它使用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.基于 Brian Diggs 的回答,它在轮廓之间填充颜色:这是具有不同 alpha 级别的等价物,并添加了透明点以进行比较。
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()
Combining two other answers (one pointing to geom_density2d
and one giving sample data and scale_colour_gradient
):结合其他两个答案(一个指向
geom_density2d
和一个给出样本数据和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")
There's also scale_colour_gradient()
还有
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.