Size of the panels with facet_wrap

7

I'm doing some panel graphics in 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)

Ihavemygraphicalwindowseparatedinto10distinctpanels,becausetransisacategoricalvariablewith10levels.However,ifIuseanothervariableforthepanels,theresultIgetisthis:

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

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

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

What should I do, so that when creating two panels with a different number of panels, they all have the same size? That is, how do you leave the two panels of the chart with facet_wrap(~ as.factor(year)) with the same size as the chart panels with facet_wrap(~ trans) ?

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

    
asked by anonymous 13.09.2018 / 18:15

1 answer

7

In this 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)

grid.newpage()grid.draw(g2)

    
13.09.2018 / 19:59