I'm using facet_wrap with ggplot to create a plot of facets. My problem is that my facets always come out looking like very short, very wide rectangles, but I want them to be square so they are easier to understand. Ideally, I would like to specify the number of columns I desire, and have ggplot figure out what the height of the plot should be so that all the facets are square. Is this possible?
Asked
Active
Viewed 5,527 times
9
-
1`library(fortunes); fortune("Yoda")` -- "Simon Blomberg: This is R. There is no if. Only how." You'll need to count the total number of facets (i.e. number of levels of your faceting variable), divide by the number of columns to get the number of rows, and use `ggsave()` to save a plot with the right overall aspect ratio ... accounting for the decoration (legends, axes labels, etc.) might make it a little harder but you can probably get close. – Ben Bolker Jan 22 '14 at 22:26
-
You may want to put your facets into separate plots and arrange them with `grid.arrange(...)`. Read the documentation on the `gridExtra` package, especially `grid.layout(...)` and `grid.arrange(...)`. Otherwise, provide a representative sample of your data and show us what you are getting now. – jlhoward Jan 22 '14 at 22:27
4 Answers
13
Maybe aspect.ratio
helps:
df <- data.frame(x = runif(100, 0,10), y = runif(100, 0, 50), z=gl(4,25))
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~ z, ncol = 4) +
theme(aspect.ratio = 1) # try with and without

lukeA
- 53,097
- 5
- 97
- 100
-
This didn't work for me only because I'm using an older version of ggplot. coord_fixed(1) seemed to accomplish this same thing. – andrew Jan 23 '14 at 16:56
-
Accepting this one because it should work for people with latest version of ggplot and using theme() is nicer than my solution. – andrew Jan 28 '14 at 15:31
1
Using coord_fixed(1) did the trick. Seems I'm using an older version of ggplot so theme(aspect.ratio=1) did not work for me.
df <- data.frame(x = runif(100, 0,10), y = runif(100, 0, 50), z=gl(4,25))
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~ z, ncol = 4) +
coord_fixed(1)

andrew
- 2,524
- 2
- 24
- 36
0
I understood the question slightly differently than lukeA. I thought you wanted the plots to be arranged in an n x m fashion with dimensions as close to "square" as possible.
ggplot(df, aes(x, y)) +
geom_point() +
facet_wrap(~ z, ncol = sqrt(length(levels(df$z))) )

IRTFM
- 258,963
- 21
- 364
- 487