#Load package
library("mgrtibbles")
#Set seed for random sampling
set.seed("483")
#mushroom_tbl tibble for demonstration
<- mgrtibbles::mushroom_tbl |>
mushroom_tbl #Random sample of 150 rows
::slice_sample(n = 150, replace=FALSE)
dplyr#Reset random seed to normal operation
set.seed(NULL)
Ggplotly

Plotly is a graphing library that allows you to create interactive charts and maps. These are in the form of html files.
This works with python, R, ggplot2, and other languages. You can create plots with plotly’s own library in R. However, we’ll demonstrate how to plotlyify plots with ggplot2 using ggplotly()
.
The package plotly
is separate to tidyverse
and therefore needs installing. Install instruction.
Once installed you can load the library.
Dataset
For demonstration we’ll load the mushroom_tbl
data from the mgrtibbles package (hyperlink includes install instructions). We will extract a random sample of 150 rows with slice_sample()
.
Scatter plot
To create a plotly plot from a ggplot we first create a ggplot pbject
Create a scatter plot of stem_height (y) against stem_width (x).
<- mushroom_tbl |>
scatterplot ::ggplot(aes(x = stem_width, y = stem_height)) +
ggplot2::geom_point() ggplot2
Next we can pipe the ggplot object to the function plotly::ggplotly()
.
The html based plot is interactive allowing you to:
- Zoom in horizontally, vertically, or with both axes.
- Rest the zoom with the home () symbol on the top right.
|> plotly::ggplotly() scatterplot