Horizontal/Vertical Line in plotly

There are two main ways to do this (using either data or ‘paper’ coordinates). Assuming data coordinates, the easiest current way is via add_segments():

plot_ly() %>%
  add_segments(x = 4, xend = 4, y = 0, yend = 10) %>%
  add_segments(x = 3, xend = 5, y = 5, yend = 5)

enter image description here

Notice how we’ve hard coded the extent of these lines in data coordinates; so when zooming and panning the plot, the line will be “clipped” at those values. If you don’t want these lines to be clipped, use a line shape with xref/yref set to paper (this puts the graph region on a 0-1 scale, rather than on the x/y data scale):

vline <- function(x = 0, color = "red") {
  list(
    type = "line", 
    y0 = 0, 
    y1 = 1, 
    yref = "paper",
    x0 = x, 
    x1 = x, 
    line = list(color = color)
  )
}

hline <- function(y = 0, color = "blue") {
  list(
    type = "line", 
    x0 = 0, 
    x1 = 1, 
    xref = "paper",
    y0 = y, 
    y1 = y, 
    line = list(color = color)
  )
}

plot_ly() %>%
  layout(shapes = list(vline(4), hline(5)))

enter image description here

Leave a Comment