我想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'
)
)
)
Run Code Online (Sandbox Code Playgroud)
我希望这会给出以下图表:
但相反它给出了这个:
它似乎是在错误的变量上过滤.为什么不按照我预期的方式过滤数据?
似乎问题是列表的target参数transforms只能采用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'
)
)
)
Run Code Online (Sandbox Code Playgroud)
并生成与此相同的图表
plot_ly(df %>% filter(group1=="high"), x = ~x, y = ~y, type = 'scatter',
mode = 'line',
color = ~group2
)
Run Code Online (Sandbox Code Playgroud)
当然,customdata除了使用之外,您可以使用ids等替换它,该属性plot_ly允许但不影响图表的美观.