2017-07-19 75 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 
分组