Combine ggplots into a Plotly subplot

Description

Converts ggplot objects with ‘plotly::ggplotly()’, combines them with ‘plotly::subplot()’, and keeps only one legend entry per trace name across panels. Traces with the same name are assigned the same legend group so one legend click toggles the corresponding traces in all panels.

Usage

plotly_ggplot_subplot(
  ...,
  showlegend = TRUE,
  nrows = 1,
  titleX = TRUE,
  titleY = TRUE,
  margin = 0.05,
  width = "100%",
  height = NULL,
  legend_groupclick = "togglegroup"
)

Arguments

ggplot or Plotly objects to combine.
showlegend Logical. If ‘FALSE’, hide all subplot legend entries.
nrows Number of subplot rows passed to ‘plotly::subplot()’.
titleX, titleY Logical values passed to ‘plotly::subplot()’.
margin Numeric margin passed to ‘plotly::subplot()’.
width, height Optional htmlwidget width and height. Use ‘width = "100 and a pixel ’height’ to control Plotly sizing in Quarto reports.
legend_groupclick Plotly legend group click behaviour. Use ‘NULL’ to leave the Plotly default unchanged.

Value

A Plotly htmlwidget.

Examples

library("prolfquapp")

if (requireNamespace("plotly", quietly = TRUE)) {
  p1 <- ggplot2::ggplot(mtcars, ggplot2::aes(mpg, colour = factor(cyl))) +
    ggplot2::geom_density()
  p2 <- ggplot2::ggplot(mtcars, ggplot2::aes(disp, colour = factor(cyl))) +
    ggplot2::geom_density()
  plotly_ggplot_subplot(p1, p2)
}