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?
Density can be represented in the form of 2D density graphs or density plots. A 2d density chart displays the relationship between 2 numeric variables, where one variable is represented on the X-axis, the other on the Y axis, like for a scatterplot.
The most common function for creating heatmaps in R is the heatmap () function, which is already provided by the base installation of R. The heatmap function is applied as shown below:
The heatmap function. The heatmap function has the form of heatmap (x, scale, na.rm, col, labRow, labCol, main) and it produces a heat map of the data. x is the numeric matrix containing the values being used in creating the heat map. col is the color palette to be used by the heat map.
The plotly package contains the plot_ly function, which can be used to draw a heatmap by specifying type = “heatmap”: Figure 6: Default Heatmap in plotly Package. Again, the patter is the same, but the general plot style is different.
Data science has many graphical ways of displaying data, and each provides unique types of information about the data being presented. If you want to see how a field of data is spread over a given area, a heat map is a useful tool. Heat maps illustrate the distribution of data in color changes over the surface that is being illustrated.
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()
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With