Force ggplot2 scatter plot to be square shaped

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.


Probably the ugliest code you'll see today, but it does the trick.

The ranges of your x and y axes are accessible from ggplot_build:

r<-max(abs(ggplot_build(your_plot)$panel$ranges[[1]]$x.range))
s<-max(abs(ggplot_build(your_plot)$panel$ranges[[1]]$y.range))
t<-round(max(r,s),1)
your_plot<-your_plot+coord_equal(xlim=c(-t,t),ylim=c(-t,t))

Note: for a square shape (irrespective of the data being plotted),

ggplot() + theme(aspect.ratio=1)

enter image description here