Reputation: 1346
Is there a way to add contour labels to a 2D kernel density plot made using geom_density_2d in ggplot2?
library(ggplot2)
# load data
data("meuse")
# plot
ggplot(meuse, aes(x=x, y=y)) +
geom_density_2d()
I tried extracting out the plotted data from the built ggplot object so I could pass it to geom_text_contour from metR but the data it returns is a set of points that are used to plot the contour lines, not a grid of x/y coordinates geom_text_contour would need.
# extract denisty 2d
data <- ggplot_build(p)$data[[1]]
p + geom_path(data=data,
mapping=aes(color=nlevel, group=group),
color='red')
I want to make something like this (this example is from the geom_text_contour documentation).
Upvotes: 1
Views: 749
Reputation: 563
As far as I can see, geom_text_contour
requires a geom_contour
stat, which in turn requires a raster-like object, and not a collection of points as you have here. However, there is the 'directlabels' library which can work with geom_density_2d
. This example is super ugly, but hopefully can get you started! I changed the axis scale to make the contour values more manageable.
library(directlabels)
g1 <- ggplot(meuse %>% mutate(x=x/1000, y=y/1000), aes(x=x, y=y)) +
geom_density_2d(aes(colour = ..level..))
direct.label(g1, list(top.pieces, colour = 'black'))
Upvotes: 1