0

I'd like to plot a horizontal bar chart in R's plotly and add a vertical dashed line.

Here is the data:

df <- data.frame(x = c(5,7), y = c("A","B"), bar.width = rep(0.1,2))

Here's the code I'm trying:

library(plotly)
library(dplyr)

plot_ly(data=df,marker=list(color="darkred")) %>%
  add_bars(x=~x,y=~y,width=~bar.width) %>%
  layout(xaxis=list(title="X"),yaxis=list(title=NA),orientation='h') %>%
  add_trace(x=c(2.5,2.5),y=c(0,1),mode="lines",showlegend=F,line=list(color="black",dash='dash'))

And this is what I'm getting: enter image description here

And these warning messages:

No trace type specified:
  Based on info supplied, a 'scatter' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter
A marker object has been specified, but markers is not in the mode
Adding markers to the mode...
Warning message:
Can't display both discrete & non-discrete data on same axis 

Any idea?

dan
  • 6,048
  • 10
  • 57
  • 125

1 Answers1

2

One option to achieve your desired result would be to switch to a continuous scale by converting your y variable to a numeric and setting the labels via layout like so:

library(plotly)

fig <- plot_ly(data = df, marker = list(color = "darkred")) %>%
  add_bars(x = ~x, y = ~ as.numeric(factor(y)), width = ~bar.width, orientation = "h") %>%
  layout(xaxis = list(title = "X"), yaxis = list(title = NA), orientation = "h") %>%
  add_trace(
    x = c(2.5, 2.5),
    y = c(.75, 2.25),
    type = "scatter", mode = "lines", showlegend = F, line = list(color = "black", dash = "dash")
  )

fig %>%
  layout(
    yaxis = list(
      ticktext = list("A", "B"),
      tickvals = list(1, 2),
      tickmode = "array"
    )
  )

stefan
  • 90,330
  • 6
  • 25
  • 51