Skip to content

Filled contours don't play well with faceting #3875

Closed
sthagen/tidyverse-ggplot2
#10
@clauswilke

Description

@clauswilke

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:

path_df$level <- ordered(path_df$level, levels = names(isobands))

By contrast, the level variable for contour lines is a numeric:

path_df$level <- as.numeric(path_df$level)

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions