3MW (Making ggplots interactive)

Guten Tag!

Many greetings from Ulm, Germany.

Interactive plots are great. They let users focus on what matters to them. That’s why they are so popular for communicating data-driven insights.

And the good news is: They’re easy to create! Let me show you how. For your convenience, the completed code can be found on GitHub.

Start with a ggplot

The first step is easy. Basically you create a ggplot just like you normally would. For example, here’s a basic line chart.

The corresponding code is nothing too fancy. Here it is.

Add interactive parts with {ggiraph}

Next, you need to decide what parts become interactive. I want to focus on the lines and the points one at a time. Just like this:

Therefore, we need to make both geom_line() and geom_point() interactive. We do this by loading {ggiraph} and

  1. changing geom_point() to geom_point_interactive(),

  2. changing geom_line() to geom_line_interactive() and

  3. adding one of the following aesthetics in each interactive layer: tooltip, data_id or onclick.

I’ll just map data_id to continent in both layers. This way, each continent has its own interactive part (just as we’ve seen).

Notice that I saved the plot into a variable instead of generating output from the code. The magic step comes next.

Render the interactive plot with girafe()

Finally, pass our new variable to girafe(). Watch out for one thing, though. You need to call girafe(ggobj = line_chart) and not girafe(line_chart). If your plot is not interactive, make sure you did not make this particular mistake.

Tweak the interactivity

Our line chart currently turns lines orange as we hover over them. Everything else remains unchanged. Let’s change that so that all but one line turn transparent.

The way to do that is to pass a list of options to girafe(). This list will contain opts_hover() and opts_hover_inv() to determine the CSS code that needs to be applied. Also, let us fix our plot size with opts_sizing().

Here we’ve reset the hover CSS to no CSS at all. This gets rid of the orange line coloring so that all lines shine in their original color.

Combine {ggirafe} and {patchwork}

Now, let me show you one more trick. With the same logic as before we can create all kinds of plots. For example, here’s a box plot using the same data. The key function is geom_boxplot_interactive().

If our previous line chart and this box plot use the same data_id , then you can combine them using {patchwork}.

All it took to create this was to combine the plots with {patchwork} in the girafe() call.

Hope you’ve enjoyed this week’s newsletter. And don’t forget: All of the code is on GitHub.

See you next week!
Albert

Reply

or to participate.