2017-10-13 224 views
0

我想在R中使用Plotly包作为Shiny应用程序的一部分创建堆积面积图并希望比较悬停时的数据。但是,由于设计原因,我隐藏了模式栏,因此我需要在代码中声明此选项,因为当前仅在最靠近光标的数据点上显示悬停。R:将Plotly hovermode设置为“比较悬停时的数据”

但是,Plotly for R reference仅给出选项“x”(x轴上的工具提示),“y”(y轴上的工具提示),“最接近”(显示最接近光标的数据点的工具提示)和FALSE(禁用工具提示)。

有没有办法做到我想要的?请注意,这个问题与this one完全相反。

我正在使用的代码是:

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) 

其中一个数据2(简体版)是:

Year A  B 
2006 18.0 82.0 
2007 19.2 78.3 
2008 17.9 80.2 
2009 20.1 77.7 

回答

2

添加layout(hovermode = 'compare')到您的代码:

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') 

编辑 @OctavianCorlade发给我一个IM有关上述解决方案的重要提示:“以前提供的答案是有效的,因为任何与可用选项不同的字符串都会产生相同的结果。 。hovermode = 'x'是记录的方式做到这一点,实现了完全相同的结果
因此,根据@OctavianCorlade的建议,可以使用:

layout(hovermode = 'x') 

enter image description here

+0

我不知道为什么他们不”在参考指南中包含这些内容吗? –