2017-07-19 68 views
3

我正在繪製一個標準線形圖,並且想要使用標記(其中數據框中的另一列不是NA)突出顯示線圖上的特定點。此外,當我懸停在情節上時,我只想看到標記點上的y值,而不是情節的其餘部分。在標準線條圖中的特定點處添加標記

這裏是一個重複的例子,並在那裏我AVE在嘗試這樣做這麼遠:

library(plotly) 
library(dplyr) 

data <- data.frame(x = c(1:100), 
       random_y = rnorm(100, mean = 0), 
       variable = sample(c('a', 'b', 'c'), 100, replace = TRUE), 
       point = sample(c(1, rep(NA, 4)),100, replace = TRUE)) 

p <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines', color = ~variable, hoverinfo = 'none') %>% 
add_trace(data = filter(data, !is.na(point)), color = ~variable, mode = 'markers', 
      x = ~x, y = ~random_y, hoverinfo = 'y') 

這會產生什麼我之後,但問題是在圖例中。它顯示了線和標記圖的圖例。

我可以把showlegend = F作爲其中一個繪圖,但問題是,當我點擊圖例中的變量時,它不能正確地分離出痕跡。即如果我點擊圖例a我希望a的折線圖和標記顯示

回答

2

您可以使用循環爲您的變量添加過濾器數據框,併爲該行添加一個跟蹤,另一個用於標記。兩條曲線是通過legendgroup

enter image description here

library(plotly) 
library(dplyr) 

data <- data.frame(x = c(1:100), 
        random_y = rnorm(100, mean = 0), 
        variable = sample(c('a', 'b', 'c'), 100, replace = TRUE), 
        point = sample(c(1, rep(NA, 4)),100, replace = TRUE)) 

p <- plot_ly(type = 'scatter', mode = 'lines') 
for (i in levels(data$variable)) { 
    print(i) 
    p <- add_trace(p, 
       data = data[data$variable == i,], 
       legendgroup = i, 
       x = ~x, 
       y = ~random_y, 
       type = 'scatter', 
       mode = 'lines', 
       color = ~variable, 
       hoverinfo = 'none' 
) 
    p <- add_trace(p, 
       data = data[(data$variable == i) & (!is.na(data$point)),], 
       legendgroup = i, 
       showlegend = F, 
       color = ~variable, 
       mode = 'markers', 
       x = ~x, 
       y = ~random_y, 
       hoverinfo = 'y') 
} 

p 
分組