您可以使用legendgroup
并通过隐藏重复的跟踪名称showlegend
.
另请参阅:https://plotly.com/r/legend/#grouped-legend https://plotly.com/r/legend/#grouped-legend
Edit:@JulianStopp修改示例数据后:
这是寻找隐藏在图例中的痕迹的通用方法。抱歉切换到data.table
但我不熟悉dplyr
:
library(data.table)
library(plotly)
cell <- c(rep("a", 10), rep("b", 10), rep("c", 10), rep("d", 10), rep("e", 10), rep("f", 10))
group <- c(rep("Untreated", 10), rep("Treated", 30), rep("Unknown", 20))
time <- rep(1:10, times=6)
value <- c(runif(60))
DF <- data.frame(cell, group, time, value)
setDT(DF)
setorder(DF, group, cell, time)
showlegendDF <- DF[, .SD[1], by = .(group, time), .SDcols = c("cell")][, showlegend := TRUE] # find first trace for each group
DF <- showlegendDF[DF, on = c("group", "cell", "time")] # join
DF[, i := .GRP, by = .(group, cell)] # create trace indices
# set(DF, which(is.na(DF[["showlegend"]])), "showlegend", FALSE) # replace NAs with FALSE
plot_ly(DF, x=~time, y=~value, split=~cell, legendgroup = ~group, name = ~group, color = ~group,
type="scatter", mode="line") %>% style(showlegend = FALSE, traces = unique(DF[is.na(showlegend), i]))
初步回答:
library("dplyr")
library("plotly")
cell <- c(rep("a", 10), rep("b", 10), rep("c", 10))
group <- c(rep("Untreated", 10), rep("Treated", 20))
time <- c(seq(1:10), seq(1:10), seq(1:10))
value <- c(runif(30))
df <- data.frame(cell, group, time, value)
plot_ly(df, x=~time, y=~value, split=~cell, legendgroup = ~group, name = ~group, color = ~group,
type="scatter", mode="line") %>% style(showlegend = FALSE, traces = 2)