Ggplot2: aspect.ratio redistributes coding coordination or coord.fixed

I want to get a square graph with equal coordinates, whatever the shape of the cloud of my data points is.

Here is a primitive illustration of my question.

xy <- data.frame(x = rnorm(100), y = rnorm(100, mean = 1, sd = 2)) gg <- ggplot(xy,aes(x = x, y = y))+ geom_point() gg + coord_equal() #now we have square coordinate grid gg + theme(aspect.ratio = 1) #now the plot is square # if we use both, aspect.ratio overpowers coord_equal gg + coord_equal() + theme(aspect.ratio = 1) 

Is there a way to have both a graph and a grid square? Of course, there would be a few gaps in the plot. I am not against that.

In addition, I would like to find out the simplest way to ensure equal marking for both the x and y axes.

+4
source share
3 answers

You can force the graph to be square by manually setting the scale of the axes:

 gg + scale_x_continuous(limits=c(min(xy$x,xy$y), max(xy$x,xy$y))) + scale_y_continuous(limits=c(min(xy$x,xy$y), max(xy$x,xy$y))) + theme(aspect.ratio=1) 
+3
source

The easiest way is to specify x-lim and y-lim separately:

 gg + coord_equal() +xlim(c(-6,6)) + ylim(c(-6,6)) 

which you can replace again with a function that outputs min / and can be based on data ( ?extendrange ).

enter image description here

0
source

You do not need the theme() , as you can simply do this in coord_fixed() . For your example, you can do the following:

 gg <- ggplot(xy,aes(x = x, y = y))+ geom_point() gg + coord_fixed(ratio=1,xlim=c(floor(min(xy$x,xy$y)), ceiling(max(xy$x,xy$y))), ylim=c(floor(min(xy$x,xy$y)), ceiling(max(xy$x,xy$y)))) 

using ceiling and floor in x- and y-lims, you have no problem that your axes are bounded over your outer points.

0
source

All Articles