Instant Interactivity: The One-Line Magic of plotly

The previous modules taught you how to build virtually any static chart with R and ggplot2. But what if your audience could hover over data points, zoom into regions, or explore the data on their own?

This lesson introduces the plotly package, a library that turns your existing ggplot2 charts into interactive visualizations with tooltips, hover effects, and zoom options β€” with just one line of code.

Free9 minutes read

Before You Start 🧰

We’re using custom fonts in this lesson to showcase non-default styling. If you'd like to run the examples on your machine, make sure to install Rethink Sans and Domine on your system if you haven't yet.

πŸ–±οΈ Interactivity: Why?

This course has taught you a lot about ggplot2, the most powerful library for creating graphs with R. The possibilities are limitless: you can create literally anything with it.

Anything, yes. But only static outputs.

Even if that covers 95% of a data analyst's needs, it can sometimes lead to frustrating situations. Let's take the following chart for instance:

The result is pretty insightful already. But isn't it frustrating not to know which countries are behind the outliers? The circles that sit away from the main trend?

That's when interactivity comes in. Allowing to zoom in, add hover effects, tooltips, and cross-chart interactions is not always necessary β€” but it can remove a lot of frustration when exploring data.

Interactivity β€” But Only on Purpose

Don't add interactivity just because you can. A bar chart with a tooltip that shows the value of each bar is totally useless β€” the value is already encoded by the bar height and can be read from the axis.

Interactivity shines when it reveals hidden information: identifying individual points in a dense scatter plot, exploring a long time series, or filtering across linked views. If hovering doesn't tell the reader something new, it's just noise.

✨ The ggplotly() Magic

This lesson brings some good news: Thanks to the plotly package, it literally takes one line of code to transform the scatterplot above into an interactive version.

Just store the static version in a variable (often simply called p), wrap it in a ggplotly() call, and you get an interactive version of the chart:

Check the result below and make sure you noticed all the features: you can hover to see values, zoom by dragging a selection, pan to navigate, autoscale to reset, filter groups in the legend, and even download as PNG from the toolbar.

🧼 No More Tooltip Clutter

By default, ggplotly() shows every mapped aesthetic in the tooltip. For our gapminder chart, that means you'll see the raw column names and values of GDP, life expectancy, population, and continent β€” all dumped in a generic format.

It works. But it's messy.

Luckily, you can customize the tooltip content quite easily. The trick is to use the text aesthetic in your aes() call to craft exactly the tooltip you want, then tell ggplotly() to only show that:

Now hovering reveals a clean, formatted tooltip with the country name in bold, nicely labeled values, and no clutter:

πŸ”§ How Does That Work?

It's awesome to know this little ggplotly() magic trick. But to go further into interactive graphs with R, you need to develop a basic understanding of how this actually works.

There is only one way to create interactive graphs: using the programming languages of the web.

The fundamental thing to understand is that a website, at its core, is built on three technologies:

++

The foundation of the web: HTML, CSS and Javascript.
Click the logo to learn more.

Building an interactive graph means writing code in those three languages. But we are R users, not web developers! That's why libraries like plotly exist. They are wrappers: we write R code to call them, and they convert our instructions into web languages behind the scenes.

In R, these wrapper libraries are called HTML Widgets, and there are dozens of them targeting very different use cases β€” from maps (leaflet) to networks (visNetwork andnetworkD3) to tables (DT).

The plotly package is one of the most popular, specifically because of its ggplotly() function that wraps any ggplot2 chart.

πŸ’Ύ Save it β€” Share it!

Knowing how interactivity works also helps you understand how to save and share your work.

In a nutshell, you can use the following code to generate a standalone HTML file that anyone can open in a browser β€” no R, no server, no dependencies:

There are actually three main ways to view a plotly graph: in your IDE, in a Quarto report or Shiny app, and as a standalone HTML file. The video below gives you a quick tour of each option:

βš–οΈ When to Reach for Something Else

ggplotly() is a fantastic tool for quick exploration and sharing, and comes with some great interactivity features (like the clickable legend).

But when you need more control over exactly what is interactive and how the selected layers behave, things can get tricky fast.

plotly actually offers two syntaxes. We covered the ggplotly() wrapper, but there is also a lower-level syntax that gives you more flexibility.

The downside: it's an entirely new API to learn. We think you're better off switching to a package that stays closer to the ggplot2 syntax you already know β€” and that's exactly what ggiraph does. We'll explore it in depth in the next lesson!

plotly β‡’ ggplotly()ggiraph β‡’ girafe()
ApproachWrap entire ggplot in one callReplace individual geoms with interactive versions
SpeedInstant β€” one line of codeRequires reworking geom layers
Tooltip controlGlobal β€” applies to all geoms at oncePer-geom β€” choose exactly which layers are interactive
Conversion fidelityGood but imperfect β€” some ggplot features get lostNear-perfect β€” stays within the ggplot rendering
Best forQuick exploration, prototyping, data analysisPublication-quality interactive figures, reports

In addition, plotly is not native to ggplot2. That means, it squeezes some ggplot2 features into their setup. And if you are using extension packages, you can be pretty sure they won't work at all, or not perfectly, with plotly.

In short: start with ggplotly() when you want to quickly explore your data or want to benefit from their infrastructure to share and publish your work. Once you need the interactivity to be part of a polished, high-quality deliverable, move to ggiraph to enjoy all the benefits that coding visuals with R and ggplot2 offers.

πŸ† Exercises

Time to build your first interactive charts! We have prepared a set of exercises to get you started.

πŸ› οΈ Technical Note: Because plotlycharts require a live JavaScript environment that doesn't run in our code sandbox, we recommend working through these exercises in your local R environment.



← Previous

Grid Maps

Next β†’

Custom Interactivity with ggiraph