Extending ggplotly in ggplot2

How modify the plotly object after ggplot2 conversion.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Modify with Style

library(plotly)

p <- ggplot(fortify(forecast::gold), aes(x, y)) + geom_line()

fig <- ggplotly(p)

fig <- style(fig, line = list(color = 'gold'), hoverinfo = "y", traces = 1)

fig

Modify with Build

library(plotly)

p <- ggplot(fortify(forecast::gold), aes(x, y)) + geom_line()

fig <- ggplotly(p)

fig <- plotly_build(fig)

fig$x$data[[1]]$line$color <- 'blue'

fig

Modify with LayerData

library(plotly)

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
   geom_point() + geom_smooth()

fig <- p %>%
  ggplotly(layerData = 2, originalData = F) %>%
  add_fun(function(fig) {
    fig %>% slice(which.max(se)) %>%
      add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>%
      add_annotations("Maximum uncertainty", ax = 60)
  })
fig <- fig %>% add_fun(function(p) {
    fig %>% slice(which.min(se)) %>%
      add_segments(x = ~x, xend = ~x, y = ~ymin, yend = ~ymax) %>%
      add_annotations("Minimum uncertainty")
  })

fig

Reference

For more information concerning modidfying the plotly object see The Plotly Book

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)