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
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")
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()
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")