3 For Intermediate
📊 Interactive Plots in R: plotly and ggplotly
Interactive figures are extremely useful during data exploration and dashboards.
In this section, we introduce two approaches for interactivity:
ggplotly() — convert an existing ggplot2 plot into an interactive widget
plotly — build interactive plots directly using Plotly’s own grammar
3.0.1 ⭐ ggplotly(): Add Interactivity to an Existing ggplot
ggplotly() is a converter.
It takes a normal ggplot2 object and transforms it into an interactive Plotly plot, with zooming, panning, hovering, and tooltips.
✔ When to use ggplotly()
Use it when:
You already have a ggplot and want to enhance it with interactivity.
You want to keep your ggplot aesthetics, including:
facet_wrap
themes(theme_minimal(), theme_pubr(), etc.)
fill,color, andshapeaesthetics
scalesandlabels
- You want a quick, simple solution with minimal code changes.
🔧 Example
library(plotly)
p <- ggplot(mpg, aes(displ, hwy, color = class)) +
geom_point(size = 3) +
labs(
title = "Engine Size vs Highway MPG",
x = "Displacement",
y = "Highway mileage"
) +
theme_minimal()
ggplotly(p)✨ Output
Interactive scatter plot
Hover tooltips
Zooming, box selection, and legend toggling
Looks almost identical to your original ggplot
3.0.2 ⭐ Plotly (native): Build Interactive Plots Directly
Plotly also has its own plotting grammar using plot_ly().
This approach offers more control and more interactivity than converting from ggplot.
✔ When to use native plotly
Use it when:
You’re creating dashboards (Shiny, Quarto).
You want advanced interactivity
You need performance with large datasets.
🔧 Example
3.0.3 Exercises
Using the built-in mpg dataset:
- Make a histogram of hwy (highway fuel efficiency).
- Fill the bars by class.
- Use 30 bins.
- Add a title: “Highway Mileage Distribution”
- Apply theme_minimal().
- Convert your ggplot object into an interactive figure with ggplotly().
Maybe you can also try facet_wrap(~year). Try to re-plot some plots we’ve learned before.
You can also compare it to native plotly