get_dims: Find overall dimensions of a ggplot

Description Usage Arguments Details Value Author(s) See Also Examples

View source: R/get_dims.R

Description

Computes the largest possible dimensions for a fixed-aspect ggplot that still fits inside the given maximum height and width.

Usage

1
	get_dims(ggobj, maxheight, maxwidth=maxheight, units="in", ...)

Arguments

ggobj

A ggplot or gtable object.

maxheight, maxwidth

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

units

Character, giving units for the dimensions. Must be recognized by both png and grid::convertUnit, so possible values are probably limited to "in", "cm", "mm". Note especially that "px" does not work.

...

Other arguments passed to png when setting up the throwaway plot.

Details

The motivating problem: When making a ggplot with fixed panel aspect ratios, the overall dimensions of the full plot still depend on the dimensions of other plot elements: axes, legends, titles, etc. In a facetted plot, this gets even trickier: "OK, it has three panels each with aspect ratio 1.5, so that adds up to... wait, does every panel get its own y-axis, or just the leftmost one?".

ggplot apparently computes absolute dimensions for everything except the panels, so the approach taken here is to build the plot inside a throwaway graphical device, subtract off the parts of the image area used by non-panel elements, then divide the remainder up between panels. One dimension will be constrained by the size of the throwaway device, and we can then calculate the other dimension from the panel aspect ratio.

The biggest known issue with this approach is that it's inefficient, because we have to build the plot twice. I don't know of any way around this. Do you?

Value

A list containing actual image dimensions height and width, both numeric and with the same units as units.

Author(s)

Chris Black <chris@ckblack.org>

See Also

ggsave_fitmax for a convenience wrapper that calculates and plots in one step.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Extract dimensions of an existing ggplot object:
a=ggplot(mtcars, aes(wt,mpg))+geom_point()+theme(aspect.ratio=0.75)
d=get_dims(a, maxheight=12, maxwidth=8)
d
# $height
# [1] 6.138644

# $width
# [1] 8

# ==> "Oops, right. we want this plot to be wider than it is tall."

d=get_dims(a, maxheight=8, maxwidth=12)
d
# $height
# [1] 8

# $width
# [1] 10.48181

# Can now use these dimensions to set up correctly-shaped graphics output
## Not run: 
png("plot_of_a.png", height=d$height, width=d$width)
plot(a)
dev.off()

## End(Not run)

infotroph/DeLuciatoR documentation built on May 30, 2020, 10:28 p.m.