Skip to contents

Sets each x and y axis range to the extent of the data drawn on it, widened at each end by a fraction of that extent: 0 makes the data fill the plot area, 0.05 matches ggplot2's default expansion. The extent is read from the figure's traces as drawn: points and lines, bars from their base, error bars, and fills down to zero. A categorical axis (as plotly::ggplotly() draws one) spans its categories' bands, each one unit wide, so 0 puts the outer bands' edges on the plot area's.

Usage

apply_axis_padding(fig, x = NULL, y = NULL, swap = FALSE)

Arguments

fig

A plotly figure.

x, y

Padding for the x and y axes, as a fraction of the data's extent added at each end. NULL or NA leaves that axis as it is.

swap

Logical. Apply x to the figure's y axes and y to its x axes, for a plot drawn with its axes swapped (a rotated or flipped plot), so the padding follows the variable rather than the screen direction.

Value

The built plotly figure with the axis ranges set.

Details

Axes that share a scale (matched axes, or the identical ranges of a faceted plot's fixed scales) get the same range, so they still line up. Reversed axes stay reversed, and log axes are padded in log units. Axes holding dates or plotly categories, or with no numeric data on them, are left alone, as are axes marked with mark_overlay_axes().

Only what the traces draw counts. Annotations and shapes, such as significance brackets or reference lines, do not widen the range and can be cut off, so use axis limits instead on an axis that carries them.

See also

apply_uniform_styling(), which applies this from the Axes tab's "X Axis Padding" and "Y Axis Padding" inputs.

Author

Jared Andrews

Examples

fig <- plotly::plot_ly(mtcars,
    x = ~wt, y = ~mpg, type = "scatter", mode = "markers"
)
# Points reaching the edges of the plot area.
apply_axis_padding(fig, x = 0, y = 0)$x$layout$xaxis$range
#> [1] 1.513 5.424

# A ggplot area plot with its default expansion removed along x only.
df <- data.frame(year = 2000:2020, n = cumsum(c(5, rep(1, 20))))
p <- ggplot2::ggplot(df, ggplot2::aes(year, n)) +
    ggplot2::geom_area()
apply_axis_padding(plotly::ggplotly(p), x = 0)