8

By default, each plot in ggplot fits its device.

That's not always desirable. For instance, one may need to make tiles in geom_tile to be squares. Once you change the device or change the number of elements on x/y-axis, the tiles are no longer squares.

Is it possible to set hard proportions or size for a plot and fit the plot in its device's window (or make the device width and height proportional to those of the plot)?

Anton Tarasenko
  • 8,099
  • 11
  • 66
  • 91
  • 1
    Perhaps take a look at [this answer](http://stackoverflow.com/a/16368413/630863), which seems to preserve the aspect ratio of your plots. – MattLBeck Dec 14 '13 at 09:46
  • 1
    This is usually only relevant if you want to save a plot. So, use `ggsave` which allows you to pass `height` and `width` to the devices (pdf, png, ...). – Roland Dec 14 '13 at 10:00
  • 1
    @Roland Manually specifying a width and height that will make your plot area completely square is tricky, especially if you want to include legends and titles since you need to know exactly how much room these take up to account for them. – MattLBeck Dec 14 '13 at 10:04

3 Answers3

13

You can specify the aspect ratio of your plots using coord_fixed().

> library(ggplot2)
> df <- data.frame(
+     x = runif(100, 0, 5),
+     y = runif(100, 0, 5))

If we just go ahead and plot these data then we get a plot which conforms to the dimensions of the output device.

> ggplot(df, aes(x=x, y=y)) + geom_point()

If, however, we use coord_fixed() then we get a plot with fixed aspect ratio (which, by default has x- and y-axes of same length). The size of the plot will be determined by the shortest dimension of the output device.

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

Finally, we can adjust the fixed aspect ratio by specifying an argument to coord_fixed(), where the argument is the ratio of the length of the y-axis to the length of the x-axis. So, to get a plot that is twice as tall as it is wide, we would use:

> ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed(2)
datawookie
  • 1,607
  • 12
  • 20
12

A cleaner way is to use the theme(aspect.ratio) argument e.g.

library(ggplot2)
d <- data.frame(x=rnorm(100),y=rnorm(100)*1000)
ggplot(d,aes(x,y))+
geom_point() +
theme(aspect.ratio=1/10) #Long and skinny

enter image description here

coord_fixed() sets the ratio of x/y coordinates, which isn't always the same thing (e.g. in this case, where the units of x and y are very different.

Mark Payne
  • 557
  • 5
  • 12
4

Here's an easy device to treat your plot with respect,

library(ggplot2)
p = qplot(1:10, (1:10)^3)
g = ggplotGrob(p)
g$respect = TRUE
library(grid)
grid.draw(g)
baptiste
  • 75,767
  • 19
  • 198
  • 294