Reputation: 5211
I would like to filter a chart created with plotly
, based on a column of discrete values in my data. The end goal is to be able to use buttons to update the filter value, so I do not want to filter the data beforehand.
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'
)
)
)
I expected this to give the following chart:
but instead it gives this:
It seems to be filtering on the wrong variable. Why isn't the data being filtered the way I expect?
Upvotes: 3
Views: 6190
Reputation: 1364
It seems the issue is that the target
argument of the transforms
list can only take the name of a plot_ly attribute, not raw data. This code works:
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'
)
)
)
and produces the same chart as this
plot_ly(df %>% filter(group1=="high"), x = ~x, y = ~y, type = 'scatter',
mode = 'line',
color = ~group2
)
Of course, instead of using customdata
, you can replace it with ids
, etc, an attribute that plot_ly
allows but doesn't affect the aesthetics of your chart.
Upvotes: 9