Description
This is technically a bug report against my PR #3864, but the bug isn't caused by that PR, it's just revealed by it. The same bug exists with geom_contour_filled()
, just requires more code to generate a reprex.
I have noticed that when I draw filled density contours across facets, the color levels in the legend get jumbled. (Carefully look at the levels in the legend, and you'll see they're not even in order.)
library(ggplot2)
set.seed(4393)
dsmall <- diamonds[sample(nrow(diamonds), 1000), ]
ggplot(dsmall, aes(x, y)) +
geom_density_2d_filled() +
facet_grid(. ~ cut)
What happens is that the breaks are calculated separately for each facet, and then they don't match across facets. It's possible to work around this by manually specifying breaks, but I think the default settings should work with facets.
Fundamentally, the problem is that the level
variable for contour bands is an ordered factor specifying the bin boundaries:
Line 111 in db58364
By contrast, the level
variable for contour lines is a numeric:
Line 86 in db58364
I think instead we should return a numeric value for level
in all cases and by default map that to fill for filled contours. We can still return the ordered factor as well as an option, under a different name. The numeric value I would use for level
would be the mid-point between the lower and the upper level boundary. This is consistent with other binning approaches, e.g. the placement of bars in histograms.
The result would be something like the following (but without the aes(fill = ...)
statement needed):
ggplot(dsmall, aes(x, y)) +
geom_density_2d_filled(aes(fill = after_stat(level_high))) +
facet_grid(. ~ cut) +
scale_fill_viridis_c()
This will be consistent with how contour lines work already:
ggplot(dsmall, aes(x, y)) +
geom_density_2d(aes(color = after_stat(level))) +
facet_grid(. ~ cut) +
scale_color_viridis_c()
If we agree on this approach I'll incorporate it into #3864.