Make a plot interactive in HTML output

Description

Wraps a ggplot2 plot so that it is interactive in HTML output (via plotly::ggplotly()) and unchanged in all other output formats, such as PDF or Word.

Usage

interactive_plot(plot, alt, is_html = knitr::is_html_output())

Arguments

plot A ggplot2 plot object.
alt A single non-empty string giving the text alternative (alt text) for the plot. Checked in every output format, so a missing alt text fails the render of the PDF handout too.
is_html Whether the current output format is HTML. Defaults to knitr::is_html_output(), which detects the format of the document being rendered.

Details

In HTML output, the interactive plot is placed inside a <div> with role = “img” and aria-label = alt, so that screen readers announce the plot as a single image with the text alternative alt, rather than traversing the internals of the plotly widget.

Value

If is_html is FALSE, plot, unchanged. Otherwise, an htmltools::div() tag containing the interactive plotly widget.

Examples

Code
library("qnp")


p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) +
  ggplot2::geom_point()

# non-HTML output: the ggplot is returned unchanged
interactive_plot(
  plot = p,
  alt = "Scatterplot of fuel economy versus car weight",
  is_html = FALSE
)

Code
# HTML output: an interactive widget wrapped in an accessible `div`
interactive_plot(
  plot = p,
  alt = "Scatterplot of fuel economy versus car weight",
  is_html = TRUE
)