Reputation: 3162
I've got a chart that shows two kinds of data and the forecast for them for further months. I use hovermode = "x"
to get hover for two lines at the same times. And everything works but... in the part, where amount
is equal to forecast
the hover is doubled. It is quite logical but I would like to get rid of one of this values. Do you know how to deal with it?
My data:
dane <- structure(list(month = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
amount1 = c(1086L, 1027L, 1024L, 1080L, 1072L, 1144L, NA, NA, NA, NA, NA, NA),
amount2 = c(1057, 1067, 1068, 1060, 1056, 1040, NA, NA, NA, NA, NA, NA),
amount1_forecast = c(NA, NA, NA, NA, NA, 1144L, 1119L, 1165L, 1145L, 1170L, 1158L, 1115L),
amount2_forecast = c(NA, NA, NA, NA, NA, 1040L, 1178L, 1122L, 1145L, 1158L, 1175L, 1119L)),
row.names = c(NA, -12L),
.Names = c("month", "amount1", "amount2", "amount1_forecast", "amount2_forecast"),
class = "data.frame")
My plot:
library("plotly")
wyk <- plot_ly(dane, x = ~month)
wyk %>%
add_trace(y = ~amount1,
type = "scatter",
mode = "lines+markers",
marker = list(color = "blue"),
line = list(color = "blue")) %>%
add_trace(y = ~amount1_forecast,
type = "scatter",
mode = "lines+markers",
marker = list(color = "blue"),
line = list(color = "blue", dash = "dot"),
showlegend = FALSE) %>%
add_trace(y = ~amount2,
type = "scatter",
mode = "lines+markers",
marker = list(color = "red"),
line = list(color = "red")) %>%
add_trace(y = ~amount2_forecast,
type = "scatter",
mode = "lines+markers",
marker = list(color = "red"),
line = list(color = "red", dash = "dot"),
showlegend = FALSE) %>%
layout(hovermode = "x") -> wyk
wyk
Thanks for any idea!
PS I know, that without option hovermode = "x"
it works but I would like to keep it ;)
Upvotes: 0
Views: 1028
Reputation: 3162
Ok, I've came up with such an idea:
library("dplyr")
dane %>%
mutate(amount1_hover = ifelse(is.na(amount1_forecast), amount1, NA),
amount2_hover = ifelse(is.na(amount2_forecast), amount2, NA)) -> dane
wyk <- plot_ly(dane, x = ~month)
wyk %>%
add_trace(y = ~amount1,
type = "scatter",
mode = "lines+markers",
text = dane$amount1_hover,
hoverinfo = "text",
marker = list(color = "blue"),
line = list(color = "blue")) %>%
add_trace(y = ~amount1_forecast,
type = "scatter",
mode = "lines+markers",
text = ~amount1_forecast,
hoverinfo = "text",
marker = list(color = "blue"),
line = list(color = "blue", dash = "dot"),
showlegend = FALSE) %>%
add_trace(y = ~amount2,
type = "scatter",
mode = "lines+markers",
marker = list(color = "red"),
text = dane$amount2_hover,
hoverinfo = "text",
line = list(color = "red")) %>%
add_trace(y = ~amount2_forecast,
type = "scatter",
mode = "lines+markers",
marker = list(color = "red"),
text = ~amount2_forecast,
hoverinfo = "text",
line = list(color = "red", dash = "dot"),
showlegend = FALSE) %>%
layout(hovermode = "x")
But maybe somebody knows better solution!
Upvotes: 1