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.

7 thoughts on “Get the best from ggplotly

  1. Hello, Thanks for the great post. Unfortunately the customized hover text doesn’t match the data points. For instance, the blue top right point is displayed as (5.4, 3.5) where it is actually (7.9, 3.8)

    Plotly matches the datapoints wrong in this case.

    This solution works:

    g <- ggplot(iris, aes(Sepal.Length, Sepal.Width, shape=Species
    ,text=paste("Sepal Length = ", iris$Sepal.Length, "\n"
    ,"Sepal Width = ", iris$Sepal.Width, "\n"
    ,"Row Number: ",rownames(iris), sep="")
    ,color=Species)) +
    geom_point(size=6, alpha=0.6)
    ggplotly(g, tooltip="text")

  2. I see you don’t monetize your blog, don’t waste your traffic,
    you can earn extra bucks every month. You can use the best adsense
    alternative for any type of website (they approve all websites), for more
    info simply search in gooogle: boorfe’s tips monetize your website

  3. 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)


Leave a Reply

Your email address will not be published.