Skip to contents

Shows or hides the legend and sets the font family, color and sizes of its title and entry labels, so the "Legend" UI inputs behave consistently across plot types. Existing legend settings (orientation, position, and any font property not supplied) are preserved because plotly::layout() merges the supplied attributes into the current layout. NULL, NA or blank values are ignored, leaving the corresponding property untouched.

Usage

apply_legend_styling(
  fig,
  title.size = NULL,
  text.size = NULL,
  position = NULL,
  font.family = NULL,
  font.color = NULL,
  show = NULL
)

Arguments

fig

A plotly figure object.

title.size

Numeric font size for the legend (or colorbar) title, or NULL to leave unchanged.

text.size

Numeric font size for the legend entry labels (or colorbar tick labels), or NULL to leave unchanged.

position

Optional length-2 vector c(x, xanchor) placing the legend horizontally, e.g. c(1.02, "left"). NULL (the default) leaves the position unchanged.

font.family

Character font family for the legend title and entry labels (and colorbar title and ticks), or NULL to leave unchanged.

font.color

Character color for the legend title and entry labels (and colorbar title and ticks), or NULL to leave unchanged.

show

Logical. FALSE hides the legend and every colorbar; TRUE or NULL (the default) leave their visibility unchanged.

Value

The plotly figure with the requested legend styling applied. Returns the figure unchanged when fig is NULL or nothing valid is supplied.

Details

Numeric colour mappings (for example fill.by/color.by on a continuous variable) are rendered as a colorbar rather than a categorical legend. The layout-level legend font and visibility do not affect a colorbar, so the colorbar title and tick fonts are updated directly on each trace (and on any shared coloraxis) using the same values, and hiding the legend turns each colorbar's showscale off. This keeps the "Legend" controls functional for both categorical and continuous legends.

Author

Jared Andrews

Examples

fig <- plotly::plot_ly(iris,
    x = ~Sepal.Length, y = ~Sepal.Width,
    color = ~Species, type = "scatter", mode = "markers"
)
apply_legend_styling(fig, title.size = 16, text.size = 10, font.family = "Courier New")
apply_legend_styling(fig, show = FALSE)