Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting panel sizes in theme() #6094

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

teunbrand
Copy link
Collaborator

@teunbrand teunbrand commented Sep 9, 2024

This PR aims to fix #5338.

Briefly, the layout object gets a new method that sets the panel sizes.

The gist is that you can give a vector of units to theme(panel.widths) or theme(panel.heights) that then applies to each panel. It overrules any aspect ratios set in the coord or theme.

Somewhat special behaviour occurs if you give a unit of length 1, but you have multiple panels. In that case, the total panel area is set, rather than the size of individual panels.

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_grid(~ drv)

# Square 2x2cm panels
p + theme(
  panel.widths = unit(c(2, 2, 2), "cm"),
  panel.heights = unit(2, "cm")
)

# Total width is 6cm, so every panel is somewhat narrower than 2cm
p + theme(
  panel.widths = unit(6, "cm"),
  panel.heights = unit(2, "cm")
)

Created on 2024-09-09 with reprex v2.1.1

I'm not quite sure whether the layout is the correct place for the method. It can also belong to the facet class, for example.

@teunbrand
Copy link
Collaborator Author

Currently interacts with {patchwork} like so:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2
library(patchwork)

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point()

p1 <- p + theme(panel.widths = unit(6, "cm"))
p2 <- p + theme(panel.widths = unit(4, "cm"))

Patchwork just ignores the sizes normally:

p1 / p2

But can preserve space when the plots are freed. It'd be neat if we could align this on the left or right side of the plot.

free(p1) / free(p2)

Created on 2024-09-09 with reprex v2.1.1

R/layout.R Show resolved Hide resolved
@thomasp85
Copy link
Member

With dev patchwork it now works in the sense that the dimensions gets adopted from the panel with the largest dimensions (if set in absolute units)

There is really no way to accommodate conflicting sizes while keeping the alignment model of patchwork so something got to give

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Panel-based sizing of figures
2 participants