geom_text_contour with geom_density_2d
dhicks opened this issue · 2 comments
Context: I'm interested in using geom_text_contour()
to direct label some calculated density contours, which I'm using to hack some group highlighting that can accommodate lots of outliers.
I'm having trouble combining geom_text_contour()
with the density contours calculated as in geom_density_2d()
. MWE:
library(tidyverse)
library(metR)
#>
#> Attaching package: 'metR'
#> The following object is masked from 'package:purrr':
#>
#> cross
library(palmerpenguins)
data('penguins')
ggplot(penguins, aes(bill_length_mm,
flipper_length_mm,
color = species)) +
geom_point(alpha = 0.5) +
geom_density_2d(data = ~ filter(.x,
species %in% c('Adelie', 'Gentoo')),
breaks = .001) +
geom_text_contour(aes(label = species),
data = ~ filter(.x,
species %in% c('Adelie', 'Gentoo')),
stat = 'density_2d',
breaks = c(.001))
#> Warning: Removed 2 rows containing non-finite values (`stat_density2d()`).
#> Removed 2 rows containing non-finite values (`stat_density2d()`).
#> Warning: Removed 2 rows containing missing values (`geom_point()`).
Created on 2023-03-21 with reprex v2.0.2
geom_density_2d()
has the behavior I'm looking for, drawing a single contour around most of the data for each of the groups of interest. What I need to do is direct label those contours, ideally with one label on each contour. I can't seem to get geom_text_contour()
to pick up those contours, though. The default "text_contour"
stat needs a separate z
aesthetic. So I thought I'd pass it the "density_2d"
stat used by geom_density_2d()
. But this results in the group labels placed directly on top of each other and not particularly close to the contours.
This is weird, but I'd never used geom_text_contour()
with a different stat. I'll look into it. In the meantime, though, you might want to check out the ggpath package.
Hi! This took forever, sorry!
Looking at the code, the issue is that geom_text_contour()
computes the contours in the stat. But the density_2d
stat doesn't output contours, but a 2D density grid. I don't think geom_text_contour()
can help here.