This is a cross-post from RStudio Community here in August and here in June. A couple of weeks ago, I also opened an issue in r-plotly here. I'm still not sure whether solving this problem requires additional plotly
features, or if I'm missing something.
This is almost a duplicate of a 2016 SO post with a similar problem. This post is different because: (1) it requires using plotly
(not highcharter.js
), (2) it requires that a tooltip will appear on hover anywhere along a segment, e.g. not at just n
points along the segment, and (3) minor syntax changes in r-plotly since 2016.
Problem
In plotly, you can use add_segments() to add line segments between two points.
How can I show the user a tooltip when hovering over anywhere on the segment, not just either end? This seems like it should be feasible from a javascript perspective, but I can't seem to get it to work with plotly.
Example:
library(plotly)
my_data <- data.frame(
x = c(1, 6), xend = c(5, 10),
y = c(1, 2), yend = c(1, 2),
text = c("First", "Second")
)
plot_ly(my_data, x = ~x, xend = ~xend, y = ~y, yend = ~yend,
text = ~text, hoverinfo = "text") %>%
add_segments()
See a gif demonstration here (Didn't embed since it's a little annoying while reading text)
Almost-solution
In the similar 2016 SO post, 'dww' provides a fantastic workaround by generating many points close together, and then using add_trace
:
NP=100
mydat <- data.frame(t1=seq(1,3,len=NP), t2=seq(4,5,len=NP), y1=rep(1,NP), y2=rep(2,NP))
plot_ly(data=mydat) %>%
add_trace(x=~t1, y=~y1, mode="lines", hoverinfo="text", text="hello") %>%
add_trace(x=~t2, y=~y2, mode="lines", hoverinfo="text", text="there")
This solution is very helpful but doesn't answer this question because (1) once the user zooms past a certain point, they will no longer have access to the tooltip (see gif below), and (2) this solution is computationally-intensive--with hundreds of traces, I am unnecessarily generating thousands of unneeded points.
TL
Using the R port of plotly
(or javascript), can I produce a segment (compatible with two continuous cartesian axes) that has its own tooltip?