Skip to content

Conversation

teunbrand
Copy link
Collaborator

This PR aims to fix #6370.

Briefly, plot_dim() receives width and height separately in addition to plot, to be able to use absolute plot dimensions for plot output. This is achieved by using the derive() flag for width and/or height.

In plot below, the width is absolute, whereas height is not. By using derive() we set the absolute width of the plot, but as the height is not absolute, we fall back to the device size.

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

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  theme(panel.widths = unit(10, "in"))

file <- tempfile(fileext = ".png")
ggsave(file, plot = p, width = derive(), height = derive())
#> Saving 10.6 x 5 in image

knitr::include_graphics(file)

Created on 2025-03-20 with reprex v2.1.1

}

if (is.unit(width)) {
if (has_null_unit(width)) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The assumption here is that if the plot dimensions contain "null" units, the dimension is relative. If these are absent, the plot is assumed to have absolute dimensions.

It is possible for facet or axis guide extensions to break this assumption (as did facet_null()).

@thomasp85
Copy link
Member

I feel like we have been here before? You cannot know how much space a graphics device needs for text so you cannot apriori know the size needed for a plot with fixed panel size. Also, width and height might be linked, either because of a fixed aspect ratio or because one depend on the either due to e.g. text wrapping.

Unless this has magically been fixed I strongly feel ggplot2 shouldn't make promises about being able to do this

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.

Easy way to use absolute plot size in ggsave()

2 participants