rggplot2

ggplot - automatically adjust axis ranges so that they are the same


I am looking for a way to automatically adjust axis ranges in ggplot so that the x axis and the y axis always have the same range.

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

enter image description here

Here we can see that the x-axis ranges from 10 to 35, and the y-axis from 1.5 to 5.5 (approximately).

If I wanted to do this manually, it would be easy:

ggplot(mtcars, aes(x = mpg, y = wt)) + 
  geom_point() + 
  xlim(1.5, 35) + 
  ylim(1.5, 35)

enter image description here

However that is not really easy to do outside of this simplified example, so I would like to find a way to automatically make the axes ranges same.


Solution

  • tidymodels::coord_obs_pred() is close to what you want, although it also sets the aspect ratio to 1 by default. You can change it to a different value by specifying the fixed argument, but AFAICT you can't easily change it back to "free" (i.e., whatever the current shape of the graphics window suggests).

    library(tidymodels)
    gg0 <- ggplot(mtcars, aes(x = mpg, y = wt)) +  geom_point()
    gg0 + coord_obs_pred()