根据分类变量过滤 plotly 折线图

Filter a plotly line chart based on categorical variable

我想根据我数据中的一列离散值过滤使用 plotly 创建的图表。最终目标是能够使用按钮来更新过滤值,所以我不想事先过滤数据。

library(plotly)    

df <- data.frame(group1 = rep(c('low', 'high'), each = 25),
                 x = rep(1:5, each = 5),
                 group2 = letters[1:5],
                 y = c(runif(25, 0, 2), runif(25, 3, 5)))

plot_ly(df, x = ~x, y = ~y, type = 'scatter',
        mode = 'line',
        color = ~group2,
        transforms = list(
            list(
                type = 'filter',
                target = ~group1,
                operation = '=',
                value = 'high'
            )
        )
)

我预计这会给出以下图表:

但它给出了这个:

似乎过滤了错误的变量。为什么数据没有按我预期的方式过滤?

看来问题是 transforms 列表的 target 参数只能采用 plot_ly 属性的名称,而不是原始数据。此代码有效:

library(plotly)    

set.seed(1)
df <- data.frame(group1 = rep(c("low", "high"), each = 25),
                 x = rep(1:5, each = 5),
                 group2 = letters[1:5],
                 y = c(runif(25, 0, 2), runif(25, 3, 5)))

plot_ly(df, x = ~x, y = ~y, customdata=~group1, type = 'scatter',
        mode = 'line',
        color = ~group2,
        transforms = list(
          list(
            type = 'filter',
            target = 'customdata',
            operation = '=',
            value = 'high'
          )
        )
)

并生成与此相同的图表

plot_ly(df %>% filter(group1=="high"), x = ~x, y = ~y, type = 'scatter',
        mode = 'line',
        color = ~group2
)

当然,您可以将其替换为 idsplot_ly 允许但不影响图表美观的属性,而不是使用 customdata