Skip to contents

ggplotly() 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).

Usage

apply_facet_subplot_spacing(fig, spacing = 0.04, ncol = NULL, nrow = NULL)

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 vector c(horizontal, vertical) to control the gap between columns and rows independently. Must satisfy horizontal * (ncol - 1) < 1 and vertical * (nrow - 1) < 1; otherwise the figure is returned unchanged.

ncol

Optional integer. Number of facet columns. If NULL or NA, detected from the number of distinct x-axis domain starts.

nrow

Optional integer. Number of facet rows. If NULL or NA, 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.

Author

Jacob Martin

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)