Muon
Muon

Reputation: 1346

ggplot2: Add contour labels to kernel density plot produced with geom_density_2d

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

enter image description here

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')

enter image description here

I want to make something like this (this example is from the geom_text_contour documentation).

enter image description here

Upvotes: 1

Views: 749

Answers (1)

Dan Slone
Dan Slone

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'))

contour plot with contours labeled

Upvotes: 1

Related Questions