How to fix aspect ratio in ggplot?

I am trying to resize the plot to fit my document, but I am having difficulty making the plotted chart square.

Example:

pdf(file = "./out.pdf", width = 5, height = 5) p <- ggplot(mydata, aes(x = col1, y = col2)) print(p) aux <- dev.off() 

Although the limits for x and y are the same, the graph is not square as a result. I assume that R makes the 5x5 "cover panel, but does not care about the actual size of the chart.

How can I cancel my charts?

+50
r ggplot2
Aug 14 '11 at 12:36
source share
3 answers

In ggplot mechanism for maintaining the aspect ratio of your plot is to add a coord_fixed() layer to the plot. This will preserve the aspect ratio of the plot itself, regardless of the shape of the actual bounding box.

(I also suggest that you use ggsave to save the result in pdf / png / etc, rather than in the sequence pdf(); print(p); dev.off() .)

 library(ggplot2) df <- data.frame( x = runif(100, 0, 5), y = runif(100, 0, 5)) ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed() 

enter image description here

+71
Aug 14 '11 at 3:26 a.m.
source share

To provide a specific aspect ratio, for example. for the square, use theme(aspect.ratio=1) .

Andri's answer does not give a complete picture, since the example gives possibly unnatural data, where the range x is equal to the range y. If, however, the data were:

 df <- data.frame( x = runif(100, 0, 50), y = runif(100, 0, 5)) ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed() 

then the graph will look like this:

enter image description here

The Coord_fixed () function also has an argument to adjust the axis relationship:

ratio expressed as y / x

So that the graph can be made square with:

 ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed(ratio=10) 

enter image description here

But you need to configure this with the limitations of variables or chart areas (not all limits are well divided by integers like these examples).

+44
Oct 06 '13 at 9:38
source share

For completeness: If you want to take into account very different axle limit values:

 df <- data.frame( x = runif(100, 0, 5000), y = runif(100, 0, 5)) ratio.display <- 4/3 ratio.values <- (max(df$x)-min(df$x))/(max(df$y)-min(df$y)) plot <- ggplot(df, aes(x=x, y=y)) + geom_point() plot + coord_fixed(ratio.values / ratio.display) 

Result:

+5
Jul 31 '15 at 15:24
source share



All Articles