2017-10-13 228 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

我不知道爲什麼他們不」在參考指南中包含這些內容嗎? –