Skip to Content
Course content

65: Interactive Visualizations with plotly

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was presenting a complex scatter plot of server latency across fifty different regions to my CTO. I had spent hours perfecting the ggplot2 aesthetic—the colors were right, the facets were clean, and the labels were crisp. But then he pointed to a single, lonely outlier floating far above the rest of the data and asked, "Which specific cluster is that, and why is it spiking?"

I spent the next three minutes scrolling through a dataframe in the console, filtering by coordinates, and trying to find the ID of that one point while the meeting went silent. It was an embarrassing realization: static plots are great for papers, but for exploration and presentations, they're often a bottleneck. That's exactly why I started using plotly. It turns your data into something you can actually touch.

Bridging the Gap with ggplotly

If you've already mastered ggplot2, you don't actually have to learn a whole new plotting grammar to get started. The plotly package provides a wrapper called ggplotly() that takes a static ggplot object and renders it as an interactive HTML widget. It's almost like magic—it preserves your scales and colors but adds zooming, panning, and hover-tooltips automatically.

library(ggplot2)
library(plotly)

# Create a standard ggplot
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + 
     geom_point() + 
     labs(title = "Fuel Efficiency vs Weight")

# Turn it interactive
ggplotly(p)

I usually use this approach when I'm in the "exploratory" phase of a project. I can build my plot quickly using the ggplot syntax I know by heart, and then wrap it in ggplotly() to hunt for those outliers that I might have missed in a flat image.

Building Native Interactive Plots

While the wrapper is convenient, building plots directly with plot_ly() gives you much finer control over the interactivity. One thing that trips people up is the syntax: plotly uses the tilde ~ before column names. This is because plotly isn't just looking for a vector; it's looking for a mapping to the data frame.

When you use the native API, you can specify the "mode" of the plot—whether you want markers, lines, or both—which allows you to create highly customized dashboards. For example, look at how we can create a bubble chart where the size of the point is tied to a third variable:

plot_ly(data = mtcars, 
         x = ~wt, 
         y = ~mpg, 
         size = ~hp, 
         color = ~factor(cyl), 
         type = 'scatter', 
         mode = 'markers',
         text = ~paste("Car:", rownames(mtcars))) %>%
  layout(title = 'Engine Performance Explorer',
         xaxis = list(title = 'Weight'),
         yaxis = list(title = 'Miles Per Gallon'))

Refining the Hover Experience

The real power of an interactive plot isn't just the zoom; it's the information you provide when the user hovers over a point. By default, plotly shows the X and Y coordinates, but that's rarely enough. Using the text argument in plot_ly() or the text aesthetic in ggplot2 allows you to pass a custom string—often created with paste0()—to give the user a full story about that specific data point.

I've found that the most effective plots are the ones where the user doesn't have to ask "What is this point?" because the hover label already told them. Whether it's a timestamp, a client ID, or a specific error message, that context is what transforms a chart into a tool.




📋 Practical Task

Build a Global Temperature Anomaly Explorer

Your goal is to create an interactive time-series visualization that allows a user to explore temperature changes over time. You will use the built-in AirPassengers dataset (which we'll treat as a proxy for temperature anomalies for this exercise) to practice native plotly implementation.

Requirements:

  • Convert the AirPassengers time series object into a data frame with two columns: Month (as a date or factor) and Passengers.
  • Use plot_ly() to create a line chart (mode = 'lines+markers').
  • Customize the hover text so that it displays "Value: [Number]" and "Date: [Month]" instead of the default coordinates.
  • Add a custom layout title: "Monthly Passenger Volume Trends".
  • Ensure the X-axis and Y-axis have descriptive labels.

Success Criteria: When you hover over a point on the line, a custom tooltip should appear, and you should be able to zoom into specific years using your mouse.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.