htorque htorque - 1 year ago 150
R Question

How to fix the aspect ratio in ggplot?

I'm trying to resize a plot to fit into my document, but I'm having difficulties getting the plotted diagram do be a square.


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

Although the limits for x and y are the same, the plot in the result isn't square. I guess that R makes the enclosing panel 5x5" but doesn't care about the actual diagram size.

How can I unsquash my diagrams?

Answer Source

In ggplot the mechanism to preserve 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 you use ggsave to save your resulting plot to pdf/png/etc, rather than the pdf(); print(p); sequence.)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download