在曲线图中的特定点添加标记

时间:2017-07-19 20:46:17

标签: r plotly

我正在绘制一条曲线图,并希望使用标记突出显示线图上的特定点(数据框中的另一列不是NA)。此外,当我将鼠标悬停在绘图上时,我只想在标记点上看到y值,而不是绘图的其余部分。

这是一个可重复的例子,我到目前为止试图做到这一点:

for i, c in enumerate(plaintext):
    print('pos is %s" % (i))

这产生了我想要的东西,但问题在于传奇。它显示了线条和标记图的图例。

我可以为其中一个图表添加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的折线图和标记显示

1 个答案:

答案 0 :(得分:3)

您可以使用循环为您的变量添加过滤器数据框,并为该行添加一个跟踪,为标记添加另一个跟踪。两条跟踪都通过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
相关问题