I want to create an interactive figure of line segments or rectangles, such that each segment or rectangle gives different information when the user hovers his/her mouse over it. I looked in the htmlwidgets showcase, and I thought plotly looked promising. (I am open to other R-related methods.)
Below is a simple example. I can create a plot of the end points (t1 and t2) that provide hover information. But I would like the hover information to appear any time the user hovers over the space between the two end points).
I can add a line segment using add_trace()
, but I can't get the hover to work. And if I add the second line segment, I get an error message:
Error in plot_ly(data = mydat, x = t2, y = y, mode = "markers", hoverinfo = "text", :
requires numeric/complex matrix/vector arguments
I can add rectangles using layout()
, but again, I can't get the hover to work.
In the event that someone suggests a way to get the hover arguments to work for either approach, I would also welcome suggestions for how to code this for a large number of segments/rectangles (not just 2 as in this simple example).
Any suggestions?
mydat <- data.frame(t1=c(1, 3), t2=c(4, 5), y=c(1, 2), task=c("this", "that"))
library(plotly)
# attempt with one line segment - hover doesn't work
plot_ly(data=mydat, x=t2, y=y, mode="markers",
hoverinfo="text", text=task) %>%
add_trace(data=mydat, x=t1, y=y, mode="markers",
hoverinfo="text", text=task) %>%
add_trace(
x=c(mydat$t1[1], mydat$t2[1]), y=c(mydat$y[1], mydat$y[1]),
mode="lines", hoverinfo="text", text=mydat$task[1])
# attempt with both line segments -
# Error in plot_ly, requires numeric/complex matrix/vector arguments
plot_ly(data=mydat, x=t2, y=y, mode="markers",
hoverinfo="text", text=task) %>%
add_trace(data=mydat, x=t1, y=y, mode="markers",
hoverinfo="text", text=task) %>%
add_trace(
x=c(mydat$t1[1], mydat$t2[1]), y=c(mydat$y[1], mydat$y[1]),
mode="lines", hoverinfo="text", text=mydat$task[1]) %*%
add_trace(
x=c(mydat$t1[2], mydat$t2[2]), y=c(mydat$y[2], mydat$y[2]),
mode="lines", hoverinfo="text", text=mydat$task[2])
# attempt with rectangles - hover doesn't work
plot_ly(data=mydat, x=t2, y=y, mode="markers",
hoverinfo="text", text=task) %>%
add_trace(data=mydat, x=t1, y=y, mode="markers",
hoverinfo="text", text=task) %>%
layout(shapes=list(
list(type="rect", x0=mydat$t1[1], x1=mydat$t2[1], xref="x",
y0=mydat$y[1], y1=mydat$y[1]+0.1, yref="y",
hoverinfo="text", text=mydat$task[1]),
list(type="rect", x0=mydat$t1[2], x1=mydat$t2[2], xref="x",
y0=mydat$y[2], y1=mydat$y[2]+0.1, yref="y",
hoverinfo="text", text=mydat$task[2])
))