12.7 plotly

One of the easiest ways to make interactive graphs is with the plotly package. If you already know ggplot, plotly’s ggplotly() function can turn a static ggplot into a JavaScript interactive graph.

Let’s go back to the initial scatterplot, looking at vote total versus Baker’s percent margin of victory. I’ll tweak it slightly by adding a label option as part of the aes(), and then save the plot to a variable.

Why add the Place column as a label option? For an interactive version of this scatterplot, I’d like to be able to mouse over a point and see the city/town, not only the vote total and margin of victory. If I don’t add the Place column in the plot, it can’t show up in the tooltip.

Now if I run ggplotly on that scatterplot, I’ll get an interactive version allowing me to mouse over any point to see underlying data (Figure 12.11).

Figure 12.11: Making a scatter plot interactive with ggplotly().

This interactive version also allows users to click and drag a portion of the plot in order to zoom in – one way to examine the data excluding Boston, or zero in on areas with a lot of points clumped together.