ggsave_fitmax: Save ggplot to correctly-shaped image file

Description Usage Arguments Details Author(s) Examples

View source: R/plot.R

Description

When a ggplot has a fixed panel aspect ratio, it can be a pain to find the right dimensions for the whole plot (including axes, margins, legends, etc) when saving it to a fixed-size graphical device. ggsave_fitmax takes a ggplot object and saves it as the largest image that fits inside the specified maximum height and width. The final image dimensions will exactly match one of maxheight or maxwidth and will not exceed the other.

Usage

1
2
3
4
5
6
7
8
ggsave_fitmax(
  filename,
  plot,
  maxheight = 7,
  maxwidth = maxheight,
  units = "in",
  ...
)

Arguments

filename

Name for the output image. By default the image format is guesssed from the file extension, but this can be overridden by specifying a value for device. See ggplot2::ggsave for details.

plot

A ggplot or gtable object.

maxheight

Numeric, giving largest allowable height of the plot. The final image will exactly match one of these and will not exceed the other.

maxwidth

Numeric, giving largest allowable width of the plot.

units

One of "in", "cm", "mm", giving units for the dimensions. Note that "px" does not work.

...

Other arguments passed to ggplot2::ggsave, notably including dpi (to set pixel resolution of the output image) and limitsize (set to FALSE if you really do want an image larger than 50 inches).

Details

This is a convenience function that wraps two distinct steps: Looking up the plot dimensions using get_dims, and saving the image using ggplot2::ggsave. If you need more flexibility in either step, skip this wrapper and call get_dims directly, then pass the computed dimensions to your favorite graphics device. See the examples in get_dims for an example. The dimension lookup was motivated by the difficulty of predicting image height & width when the panels have a fixed aspect ratio, but this wrapper should work as a one-call plotting command for plots with unconstrained ratios as well. Please report any that don't work.

Author(s)

Chris Black chris@ckblack.org

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
## Not run: 
a=ggplot(mtcars, aes(wt,mpg))+geom_point()+theme(aspect.ratio=0.75)

# Saves a.pdf at 10.55 x 8 inches
ggsave_fitmax(filename="a.pdf", plot=a, maxheight=8, maxwidth=12)

# Saves a.png at 3163 x 2400 px
# == (nominally!) 10.55 x 8 inches at 300 ppi.
ggsave_fitmax(filename="a.png", plot=a, maxheight=8, maxwidth=12)

# Saves aa.jpg at 1181 x 900 px
# == 7.8 x 6 inches at 150 ppi... or 3.9 x 3 inches at 300 ppi, or 16.4 x 12.5 at 72 ppi, or...
ggsave_fitmax(filename="aa.jpg", plot=a, maxheight=6, maxwidth=9, dpi=150)


## End(Not run)

kevinwolz/hisafer documentation built on Oct. 19, 2020, 4:43 p.m.