3

Plotly offers the option to display a moveable horizontal or vertical "spikeline" by adding layout(hovermode = "x unified") or layout(hovermode = "y unified") (see documentation). For example:

library(plotly)

x <- seq(from = 0, to = 2*pi, length = 100)
y <- sin(x)
fig <- plot_ly(x = x, y = y, type = "scatter", mode = "markers")
fig <- fig %>% layout(hovermode = "x unified")
fig

creates this plot with a vertical line that follows the cursor:

enter image description here

I would like to have both the vertical and the horizontal spikeline displayed. Like this: enter image description here

I tried to modify the layout like this:

fig <- fig %>% layout(hovermode = "x unified") %>% layout(hovermode = "y unified")
# or
fig <- fig %>% layout(hovermode = c("x unified", "y unified"))
# or
fig <- fig %>% layout(hovermode = "x unified|y unified")

None of this worked. Would anybody have a suggestion?

Snoeren01
  • 343
  • 3
  • 12

2 Answers2

6

You could use spikemode with the option across in your layout for both xaxis and yaxis. Here is a reproducible example:

library(plotly)

x <- seq(from = 0, to = 2*pi, length = 100)
y <- sin(x)
fig <- plot_ly(x = x, y = y, type = "scatter", mode = "markers")
fig %>%
  layout(xaxis = list(spikemode = 'across'),
         yaxis = list(spikemode = 'across'))

enter image description here

Created on 2022-10-29 with reprex v2.0.2

As you can see both vertical and horizontal spike lines are shown.


If you only want to have the spike lines to your axis, you could use toaxis in your spikemode like this:

fig %>%
  layout(xaxis = list(spikemode = 'toaxis'),
         yaxis = list(spikemode = 'toaxis'))

enter image description here

Created on 2022-10-29 with reprex v2.0.2

As you can see this only shows the spike lines to your axis.

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Thanks for the answer. Is it possible to share the x-axis hover between two graphs? I asked another [question](https://stackoverflow.com/questions/74246323/share-x-axis-hover-from-one-graph-to-another-plotly-r) about this. – neves Oct 29 '22 at 15:03
  • 1
    Is it possible to adjust the line thickness using across? – H. berg Nov 25 '22 at 08:09
  • 1
    Hi @H.berg, Yes you could use the argument `spikethickness` in the `list` of your axis. – Quinten Nov 25 '22 at 08:15
0

Check out this resource on 3d plots - I had the same issue and applied the xaxis = list() and yaxis = list() arguments to layout() and it worked well for me.

https://plotly.com/r/3d-hover/

gloop
  • 1
  • That's a nice feature. Did you get it work for 2D Scatterplots as well? I tried by using only two dimensions and obmitting the zaxis but that didn't work. – Snoeren01 May 09 '22 at 13:28