[英]Add markers at specific points in plotly line graph
I am plotting a plotly line graph, and want to highlight specific points on the line graph using markers (where another column in dataframe is not NA). 我正在绘制一个曲线图,并希望使用标记突出显示线图上的特定点(数据帧中的另一列不是NA)。 Furthermore, when I hover over the plot I only want to see the y value when I am on the marker points, not the rest of the plot.
此外,当我将鼠标悬停在绘图上时,我只想在标记点上看到y值,而不是绘图的其余部分。
Here is a reproducible example and where I ave got so far in trying to do this: 这是一个可重现的例子,我到目前为止试图做到这一点:
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')
This produces what I am after, but the issue is in the legend. 这产生了我所追求的,但问题出在传奇中。 It shows the legend for both the line and the marker plot.
它显示了线条和标记图的图例。
I could put showlegend = F
for one of the plots but then the issue is that when I click on the variable in the legend it doesn't isolate the traces properly. 我可以将
showlegend = F
用于其中一个图,但问题是,当我点击图例中的变量时,它不能正确地隔离轨迹。 ie If I click the legend a
I would want both the line graph and marker for a
to show 即如果我点击传说
a
我想无论是线图,并标记为a
展示
You could use a loop to add the filter the dataframe for your your variables and add a trace for the line and another one for the markers. 您可以使用循环为您的变量添加过滤器数据框,并为该行添加一个跟踪,为标记添加另一个跟踪。 Both traces are grouped via
legendgroup
两条迹线都通过
legendgroup
组进行legendgroup
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.