tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.39k stars 2k forks source link

x/ylim Arguments in coord_fixed Don’t Seem to Be Applied to Contours: #5883

Closed JStorey42 closed 2 months ago

JStorey42 commented 2 months ago

I'm unsure if this is actually a feature (perhaps I'm misinterpreting or missing something in the docs) but I've observed that using the x/ylim arguments in coord_fixed (and presumably analogous functions) seem to produce different results than declaring your limits using lims(). Specifically, contours that were originally cut off due to axis limits are no longer cut off using coord_fixed() and lims() with appropriate axis limits. However, passing (the same) appropriate axis limits to the x/ylim arguments within coord_fixed() results in the correct aspect ratio and limits, however, the contours are still cut off in the same place.

Am I missing something or is this a bug?

Thanks.

A simple contour plot that requires rescaling to accommodate all contours:

ggplot(mtcars) +
  stat_density2d(aes(x = mpg, y = wt)) 

image

Correcting axis limits to accommodate all contours with lims() and applying coord_fixed() works:

ggplot(mtcars) +
  stat_density2d(aes(x = mpg, y = wt)) +
  lims(x = c(5, 45), y = c(-5, 15)) +
  coord_fixed()

image

But when correcting axis limits with x/ylim within coord_fixed(), the contours remain cutoff:

ggplot(mtcars) +
  stat_density2d(aes(x = mpg, y = wt)) +
  coord_fixed(xlim = c(5, 45), ylim = c(-5, 15))

image

thomasp85 commented 2 months ago

This is expected behaviour though I can see why it may be surprising. The contour stat uses the scale limits (which are set with lims()) to figure out the extend of the contouring. The xlim and ylim arguments in the coords are setting the coordinate limits and act more like a zoom level for the final graphical representation