Skip to content

Smarter axes limits around stat_density_2d polygons #3960

Closed
@vlepori

Description

@vlepori

Axes limits are based on points rather than on the computed contour lines/shapes. This leads to some weird cropping of polygons:

faithful %>%
  mutate(gr = if_else(row_number()%%2==0,1,2)) %>% 
  ggplot(aes(x = eruptions, y = waiting)) +
  stat_density_2d(aes(alpha = after_stat(level)), geom = "polygon")+ 
  geom_density2d(color="black")+
  facet_wrap(~gr)+
  theme_classic()

image

A fiddly way around this is to change the limits manually with blank layers:

faithful %>%
  mutate(gr = if_else(row_number()%%2==0,1,2)) %>% 
  mutate(miny=waiting-10,maxy=waiting+10,minx = eruptions-1,maxx=eruptions+1) %>% 
  ggplot(aes(x = eruptions, y = waiting)) +
  geom_density2d(color="black")+
  stat_density_2d(aes(alpha = after_stat(level)), geom = "polygon")+ 
  facet_wrap(~gr)+
  theme_classic()+
  geom_blank(aes(y = miny)) +
  geom_blank(aes(y = maxy)) +
  geom_blank(aes(x = minx)) +
  geom_blank(aes(x = maxx))

image

but this becomes quickly a nightmare if one has to do it often (even without hardcoding values). It would be nice to have the axes automatically adjust to the size of the largest polygon. Alternatively, polygon cropping should be handled differently.
Thank you, and apologies if this is already well known and/or has a solution already!

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