基于分类变量筛选plotly折线图

3

我想要筛选一个使用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'
            )
        )
)

我期望它会呈现以下图表:enter image description here,但是它给出了这个:enter image description here 它似乎在错误的变量上进行了过滤。为什么数据没有按照我的预期进行过滤呢?请帮我看看。

你有没有考虑使用Shiny来完成这个任务? - Vivek Katial
1个回答

9

看起来问题是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
)

当然,你可以将customdata替换为ids等属性,plot_ly允许使用这些属性,但不影响图表的美观。


谢谢!这非常有帮助。我无法使用“uid”属性使其工作,但其他属性可以。 - C. Braun
我自己还没有测试过uid。我会修改我的答案并删除uid。 - LmW.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接