Get the best from ggplotly

Plotly is an R library allowing to make amazing interactive charts in a minute. This blog post shows how to get the best from ggplotly, the function of plotly allowing you to turn any ggplot2 chart interactive. A special care is given on features that are not present in ggplot2 (like hovering), and features that are not well translated by ggplotly (like legend position).

Let’s start with a usual ggplot2 chart. Note that the ggplot2 section of the R graph gallery contains dozens of examples with the reproducible code, so you will most likely find the graphic you need to visualize your data.

Then, we can apply the magic of plotly in just one line of code! We get an interactive chart on which we can zoom, hover, play with axis, export, click on legend to make group appear/disappear … This is great and works with any ggplot2 graphic.

Since ggplot2 creates static charts, it does not offer any option to custom hover text. This can be done as follow: 1/ create a text vector with the text you want to show 2/ use plotly_build() to make the interactive chart 3/ pass the text to the interactive version with style()

Unfortunately, some ggplot2 parameters are sometimes misunderstood by ggplotly. For example, let’s place the ggplot2 legend inside the plot:

Using a basic ggplotly() call will not change the legend position. To do so, we need to enter parameters using the real plotly syntax as follow. Note that all plotly arguments can be found here.

Note that the R graph gallery offers a lot of other examples of interactive R charts. You can follow the gallery on Twitter or on Facebook to be notified of recent updates.

One thought on “Get the best from ggplotly

  1. A simpler way to add hover text is to add a text aesthetic to your ggplot2 layer. An example from the plotly docs:
    p <- ggplot(data = d, aes(x = carat, y = price)) +
    geom_point(aes(text = paste("Clarity:", clarity))) +
    geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)

    ggplotly(p)

Leave a Reply

Your email address will not be published.