Harry
Harry

Reputation: 451

Adjust the size of panels plotted through ggplot() and facet_grid

I have a dataframe to plot multiple panels with the same x axis and different y axis. The number of columns may vary. I use ggplot and facet_grid to plot these panels.

The problems is that the size of the overall plot seems to be the same, thus when more panels appear, the size of each one is very small.

Are there any ways to fix the size of each panel and the overall size of the figure vary depending on the number of columns and panels? Thanks.

Upvotes: 3

Views: 3035

Answers (1)

teunbrand
teunbrand

Reputation: 37923

I'm sorry for unintended self promotion, but I wrote a function a while back to more precisely control the sizes of panels. I've put it in a package on github CRAN. I'm not sure how it'd work with a shiny app, but here is how you'd work with it in ggplot2.

You can control the relative sizes of the width/height by setting plain numbers for the rows/colums.

library(ggplot2)
library(ggh4x)

df <- expand.grid(1:12, 3:5)
df$x <- 1

ggplot(df, aes(x, x)) +
  geom_point() +
  facet_grid(Var1 ~ Var2) +
  force_panelsizes(rows = 1, cols = 2, TRUE)

You can also control the absolute sizes of the panel by setting an unit object. Note that you can set them for individual rows and columns too if you know the number of panels in advance.

ggplot(df, aes(x, x)) +
  geom_point() +
  facet_grid(Var1 ~ Var2) +
  force_panelsizes(rows = unit(runif(12) + 0.1, "cm"), 
                   cols = unit(c(1, 5, 2), "cm"), 
                   TRUE)

Created on 2020-05-05 by the reprex package (v0.3.0)

Hope that helped.

Upvotes: 6

Related Questions