Reputation: 1188
Is there some way to format/modify the "x unified"
hover label in plotly?
For example, can I display the value of df$dow
(ie. day of week, which here only depends on x
) as an additional line right under the x
value on top of the label in this example?
library(plotly)
dates <- seq(as.Date('2000-01-01'), as.Date('2002-01-01'), 'day')
N <- length(dates)
df <- data.frame(date=dates, y1=cos((1:N)/60), y2 = sin((1:N)/30), dow = weekdays(dates))
p <- plot_ly(data=df, type='scatter', mode='lines') %>%
add_trace(x = ~date, y = ~y1) %>%
add_trace(x = ~date, y = ~y2) %>%
layout(hovermode = 'x unified', hoverdistance = 1)
p
Also, can I add text (like, have the label say "Date: Jun 1, 2000" instead of just "Jun 1, 2000"?
The example is in R, but if there is a JS solution that would also be appreciated.
Upvotes: 0
Views: 2155
Reputation: 1188
Looks like one possible workaround is to add a hidden trace with that information, as below. A better solution would be welcome.
Note that this relies on y=0 always being in the graph regardless of what traces are being shown (otherwise the hidden trace would affect Y axis scaling), idk if it is possible to avoid that.
library(plotly)
dates <- seq(as.Date('2000-01-01'), as.Date('2002-01-01'), 'day')
N <- length(dates)
df <- data.frame(date=dates, y1=cos((1:N)/60), y2 = sin((1:N)/30), dow = weekdays(dates))
htext <- sprintf('%s\n%s', df$date, df$dow)
p <- plot_ly(data=df, type='scatter', mode='lines', source = 'Z') %>%
add_trace(x = ~date, y = 0, hoverinfo='text', text = htext,
mode = 'markers', marker=list(size=0, color='white'),
showlegend=FALSE, opacity=0) %>%
add_trace(x = ~date, y = ~y1, hoverinfo='y+name') %>%
add_trace(x = ~date, y = ~y2, hoverinfo='y+name') %>%
layout(hovermode = 'x unified', hoverdistance = 1)
p
Upvotes: 1