Search code examples
rplotlyhorizontal-line

How to plot horizontal lines between y-axis ticks in plotly?


Here is some example code to illustrate my issue.

library(plotly)

p <- plot_ly(x = mtcars$mpg, y = seq_along(rownames(mtcars)), text=rownames(mtcars),
             type = 'scatter', mode = 'markers')


ax <- list(
  title = "",
  ticktext = rownames(mtcars),
  tickvals = seq(1,32)
)


line <- list(
  type = "line",
  line = list(color = "pink"),
  xref = "x",
  yref = "y"
  layer = 'below'
)

lines <- list()
for (i in seq_along(rownames(mtcars))) {
  line[["x0"]] <- mtcars$mpg[i] - 1
  line[["x1"]] <- mtcars$mpg[i] + 1
  line[c("y0", "y1")] <- i
  lines <- c(lines, list(line))
}

p <- layout(p, title = 'Highlighting with Lines', shapes = lines, yaxis=ax)
p

I would like to add horizontal lines through the plot to separate each y-axis label. I would prefer the line split the labels as well as the graph, but splitting just the graph would suffice. I have looked extensively through the plotly reference but have yet to find anything that appears to help. I was told that there might be some sort of solution through some custom JS in the y-axisof the layout section, but am unsure on how I would go about this / am not very JS savvy.


Solution

  • I was able to accomplish this by adding more lines to the lines list. Under the for loop shown above, if you add the code:

    for (i in seq_along(rownames(mtcars))) {
      line[["x0"]] <- 10 
      line[["x1"]] <- 35
      line[c("y0", "y1")] <- i-.5
      lines <- c(lines, list(line))
    }
    

    It will place a separating line in between each of the data lines.