I am trying to create a stacked area chart in R using the Plotly package as part of a Shiny app and would like to compare the data on hover. However, I am hiding the mode bar for design reasons, so I need to declare this option in my code as currently the hover is only shown for the closest data point to the cursor.
However, the Plotly for R reference only gives the options "x" (tooltip on the x-axis), "y" (tooltip on the y axis), "closest" (shows the tooltip for the closest data point to the cursor) and FALSE (disables the tooltip).
Is there a way to do what I would like? Note that this question is pretty much the complete opposite of this one.
The code I'm using is:
plot_ly(data2,
x = ~Year,
y = ~B,
name = 'In-centre',
type = 'scatter',
mode = 'none',
fill = 'tozeroy',
fillcolor = '#F5FF8D',
hoverinfo = 'y') %>%
add_trace(y = ~A,
name = 'At home',
fillcolor = '#50CB86',
hoverinfo = 'y') %>%
layout(xaxis = list(title = "",
showgrid = FALSE,
tickangle = 270,
dtick = 1,
tickfont = list(size = 11)),
yaxis = list(title = "",
ticklen = 8,
tickcolor = "#EEEEEE",
range = c(-2, 101),
tick0 = 0,
dtick = 10,
tickfont = list(size = 11)),
showlegend = TRUE,
legend = list(x = 0,
y = -0.2,
orientation = "h",
traceorder = "normal"),
margin = list(t = 25, b = 50, r = 10, l = 40)) %>%
config(displayModeBar = FALSE)
where a (simplified version of) data2 is:
Year A B
2006 18.0 82.0
2007 19.2 78.3
2008 17.9 80.2
2009 20.1 77.7
Add layout(hovermode = 'compare')
to your code:
data2 <- read.table(text="
Year A B
2006 18.0 82.0
2007 19.2 78.3
2008 17.9 80.2
2009 20.1 77.7
", header=T)
library(plotly)
library(dplyr)
plot_ly(data2,
x = ~Year,
y = ~B,
name = 'In-centre',
type = 'scatter',
mode = 'none',
fill = 'tozeroy',
fillcolor = '#F5FF8D',
hoverinfo = 'y') %>%
add_trace(y = ~A,
name = 'At home',
fillcolor = '#50CB86',
hoverinfo = 'y') %>%
layout(xaxis = list(title = "",
showgrid = FALSE,
tickangle = 270,
dtick = 1,
tickfont = list(size = 11)),
yaxis = list(title = "",
ticklen = 8,
tickcolor = "#EEEEEE",
range = c(-2, 101),
tick0 = 0,
dtick = 10,
tickfont = list(size = 11)),
showlegend = TRUE,
legend = list(x = 0,
y = -0.2,
orientation = "h",
traceorder = "normal"),
margin = list(t = 25, b = 50, r = 10, l = 40)) %>%
config(displayModeBar = FALSE) %>%
layout(hovermode = 'compare')
EDIT
@OctavianCorlade sent me an important note about the solution given above: "The previously provided answer works, simply because any string different than the available options would produce the same result. hovermode = 'x'
is the documented way to do it, achieving the exact same result".
Hence, according to the suggestion of @OctavianCorlade, one can use:
layout(hovermode = 'x')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With