Drawing lines from layouts doesn't work on ggplotly

I'm trying to draw a vertical line on a ggplotly object, but I get this weird Error:

Error in FUN(X[[i]], ...) : 
  'options' must be a fully named list, or have no names (NULL)

Here is a reprex for ggplot and plotly:


library(ggplot2)
library(plotly)
set.seed(42)

# ggplotly version

ggplotly(
  ggplot(data.frame(x = rnorm(100), y = rnorm(100)), aes(x=x, y=y)) +
    geom_point()
)%>%
  layout(
    shapes = list(
      type = "line", 
      line = list(color = "gray", dash = "dot"),
      x0 = 1, 
      x1 = 1,
      y0 = 0,
      y1 = 1,
      yref = "paper"
    )
  )

# plotly version

plot_ly(x=~rnorm(100), y=~rnorm(100)) %>%
  layout(
    shapes = list(
      type = "line", 
      line = list(color = "gray", dash = "dot"),
      x0 = 1, 
      x1 = 1,
      y0 = 0,
      y1 = 1,
      yref = "paper"
    )
  )

Any idea why the first example returns an error?

Is it possible to add the vertical line in the ggplot part instead with geom_vline()?

It is and I can use add_segments from plotly as well, but for my purpose it's preferable to do It from the layout definition since I'd like to do 'relayout' in shiny.

1 Like

@cpsievert Maybe you can help me? :pray:

I tried to track down what triggers the error, but could only trace it as far as a function called ggplotly.ggplot() by first running debug(ggplotly), then executing your sample code, and walking through the execution. You could try to add more debug() calls to dig further and find the first place the error gets triggered; that might help someone with more knowledge of plotly (which is new to me) to diagnose the issue?

1 Like

This is related to known issue with layout() -- https://github.com/ropensci/plotly/issues/1333

You can workaround the problem for now by adding the shapes directly to the plotly.js figure object:

p <- ggplotly(
  ggplot(data.frame(x = rnorm(100), y = rnorm(100)), aes(x=x, y=y)) +
    geom_point()
)

p$x$layout$shapes <- list(
    if (is.null(p$x$layout$shapes)) list() else p$x$layout$shapes,
    list(
      type = "line", 
      line = list(color = "gray", dash = "dot"),
      x0 = 1, 
      x1 = 1,
      y0 = 0,
      y1 = 1,
      yref = "paper"
    )
  )
p
3 Likes

Thank You so much!
By the way, I love your book on plotly in R and I'm trying to implement the proxies in my Shiny App. The alternative was to add and delete trace every time I want to change the position of the vertical line.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.