Size of panels with facet_wrap

Asked

Viewed 377 times

7

I’m making some panel charts on ggplot2. See the example below:

library(ggplot2)
ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point() +
  geom_smooth(method="lm", se=FALSE, colour="black") +
  facet_wrap(~ trans)

inserir a descrição da imagem aqui

I have my graphical window separated into 10 separate panels as trans is a categorical variable with 10 levels. However, if I use another variable for the panels, the result I get is this:

ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point() +
  geom_smooth(method="lm", se=FALSE, colour="black") +
  facet_wrap(~ as.factor(year))

inserir a descrição da imagem aqui

Now, my chart has two panels only, because year has only two levels.

It happens that the size of the panels depends on the size of the graphic window and the amount of levels of the variable I use in facet_wrap. The more levels this variable has, the smaller the size of internal panels.

What should I do so that by creating two panel charts with a distinct number of panels, they are all the same size? That is, how to leave the two graph panels with facet_wrap(~ as.factor(year)) the same size as the chart panels with facet_wrap(~ trans)?

Note that this change must be proportional, i.e., the font size of the axes must remain constant from one graph to another.

  • 1

    Well, one way is facet_wrap(~ factor(year, levels = 1999:2008), drop = FALSE) but I bet this isn’t what you want.

  • In fact, it solves the question problem, but it doesn’t solve my real problem. The two variables I have are factors of fact and then it would be difficult to create a rule like this. Besides, I wish there weren’t empty panels.

  • I believe the function ggplotGrob() may be useful in such a case.

  • This change would have to be just in time to save the graph with img, right?

  • Yes. It’s for a report I’m writing using Rmarkdown.

1 answer

7


In that case the problem would be the blank panels

library(ggplot2)
library(grid)

grafico_1 = ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point() +
  geom_smooth(method="lm", se=FALSE, colour="black") +
  facet_wrap(~ trans)

grafico_2 = ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point() +
  geom_smooth(method="lm", se=FALSE, colour="black") +
  facet_wrap(~ as.factor(year))

g1 = ggplotGrob(grafico_1)
g1$widths

g2 = ggplotGrob(grafico_2)
g2$widths

g2$widths = g1$widths
g2$heights = g1$heights

grid.newpage()
grid.draw(g1)

inserir a descrição da imagem aqui

grid.newpage()
grid.draw(g2)

inserir a descrição da imagem aqui

  • 4

    Great trick, did not know this. One is always learning.

  • Excellent. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.