Search code examples
rggplot2scatter-plot

Force ggplot2 scatter plot to be square shaped


I can force ggplot2 scatter plot to be square shaped with the same x and y scaling using xlim() and ylim(), but it needs manual calculation of the limits. Is there any more convenient way of doing it?

By square shape I mean two requirements:

  1. The same scale on x and y axis.
  2. The equal length of x and y axis.

Solution

  • If you want to make the distance scale points the same, then use coord_fixed():

    p <- ggplot(...)
    p <- p + coord_fixed() # ratio parameter defaults to 1 i.e. y / x = 1
    

    If you want to ensure that the resulting plot is square then you would also need to specify the x and y limits to be the same (or at least have the same range). xlim and ylim are both arguments to coord_fixed. So you could do this manually using those arguments. Or you could use a function to extract out limits from the data.