Contours of density estimate

Create contour plots of a 2D density estimate using geom_density_2d.

geom density 2d — ggplot vs CanvasXpress

library(ggplot2)
library(canvasXpress)
m <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
           geom_point() +
           xlim(0.5, 6) +
           ylim(40, 110)

# contour lines
e <- m + geom_density_2d()
e
canvasXpress(e)
# \donttest{
# contour bands
e <- m + geom_density_2d_filled(alpha = 0.5)
e
canvasXpress(e)
# contour bands and contour lines
e <- m + geom_density_2d_filled(alpha = 0.5) +
            geom_density_2d(linewidth = 0.25, colour = "black")
e
canvasXpress(e)
set.seed(4393)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsmall, aes(x, y))
# If you map an aesthetic to a categorical variable, you will get a
# set of contours for each value of that variable
e <- d + geom_density_2d(aes(colour = cut))
e
canvasXpress(e)
# If you draw filled contours across multiple facets, the same bins are
# used across all facets
e <- d + geom_density_2d_filled() + facet_wrap(vars(cut))
e
canvasXpress(e)
# If you want to make sure the peak intensity is the same in each facet,
# use `contour_var = "ndensity"`.
e <- d + geom_density_2d_filled(contour_var = "ndensity") + facet_wrap(vars(cut))
e
canvasXpress(e)
# If you want to scale intensity by the number of observations in each group,
# use `contour_var = "count"`.
e <- d + geom_density_2d_filled(contour_var = "count") + facet_wrap(vars(cut))
e
canvasXpress(e)
# If we turn contouring off, we can use other geoms, such as tiles:
e <- d + stat_density_2d(
            geom = "raster",
            aes(fill = after_stat(density)),
            contour = FALSE
) + scale_fill_viridis_c()
e
canvasXpress(e)
# Or points:
e <- d + stat_density_2d(geom = "point", aes(size = after_stat(density)), n = 20, contour = FALSE)
e
canvasXpress(e)