Apply custom subplot spacing to a faceted ggplotly figure
Source:R/plot_facets.R
apply_facet_subplot_spacing.Rdggplotly() assigns panel layout via plotly domain coordinates
(fig$x$layout$xaxis*/yaxis*$domain) rather than honouring the ggplot2
panel.spacing theme option. This helper rewrites those domains so that
each facet panel has a uniform size and the gap between panels is exactly
spacing (expressed as a fraction of the plot area, e.g. 0.04).
Arguments
- fig
A plotly figure object (typically the result of
ggplotly()).- spacing
Numeric fraction of the plot area to leave between panels (default
0.04). May be a single value applied to both directions, or a length-2 numeric vectorc(horizontal, vertical)to control the gap between columns and rows independently. Must satisfyhorizontal * (ncol - 1) < 1andvertical * (nrow - 1) < 1; otherwise the figure is returned unchanged.- ncol
Optional integer. Number of facet columns. If
NULLorNA, detected from the number of distinct x-axis domain starts.- nrow
Optional integer. Number of facet rows. If
NULLorNA, detected from the number of distinct y-axis domain starts.
Value
The modified plotly figure with rewritten axis domains and remapped paper-anchored annotations/shapes. Figures with a single panel (or no layout) are returned unchanged.
Details
In addition to the axis domains, any paper-anchored layout annotations
(e.g. facet strip titles) and shapes (e.g. strip backgrounds, panel
borders) are remapped through a piecewise-linear transform built from the
old and new domain intervals, so strip labels and panel borders move with
their panels. Annotations/shapes whose xref/yref is tied to an axis
(for example "x", "y2", or "x2 domain") are left alone because they
follow the rewritten axis automatically.
The number of columns and rows can be supplied manually, or detected automatically from the distinct x / y domain starts already present in the ggplotly output.
Examples
p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) +
ggplot2::geom_point() +
ggplot2::facet_wrap(~cyl)
fig <- plotly::ggplotly(p)
apply_facet_subplot_spacing(fig, spacing = 0.05)