I’ve been having an issue with update menus functionality within r’s plot_ly package.
An approach that has previously worked for chloropleth figures doesn’t seem to work when applied to a stacked bar chart and I am unable to ascertain as to why this is happening.
Example code:
library(plotly)
# Simplified data frame for testing
test_data <- data.frame(
time = rep(1:10, each = 4),
total = rnorm(40, 100, 10),
Species_name = rep(c("Species A", "Species B", "Species C", "Species D"), 10),
mesh_grp = rep(c("Group 1", "Group 2"), 20)
)
p <- test_data %>%
plot_ly(
x = ~time,
y = ~total,
split = ~Species_name,
color =~Species_name,
type = 'bar',
transforms = list(
list(
type = 'filter',
target = ~mesh_grp,
operation = '=',
value = unique(test_data$mesh_grp)[1]
)
)) %>% layout(
barmode = "stack",
updatemenus = list(
list(
type = 'dropdown',
active = 0,
buttons = list(
list(method = "restyle",
args = list("transforms[0].value", unique(test_data$mesh_grp)[1]),
label = unique(test_data$mesh_grp)[1]),
list(method = "restyle",
args = list("transforms[0].value", unique(test_data$mesh_grp)[2]),
label = unique(test_data$mesh_grp)[2])
)
)
)
)
p
In the above I would expect the dropdown menu for “Group 1” to filter the data to include results from Species “A” and “C”. However, the result includes all species and only data for time periods that fall on odd numbers (see image). Group 1 Group 2
Any ideas as to where I am going wrong?
Many thanks in advance! 🙂
You can achieve your desired result by re-arranging your data. (I figured this out by inspecting the plotly object via plotly_json
). Would have expected that plotly
takes care of that and hence it looks like a bug to me.
library(plotly)
set.seed(123)
test_data %>%
arrange(Species_name, mesh_grp) %>%
plot_ly(
x = ~time,
y = ~total,
split = ~Species_name,
color = ~Species_name,
type = "bar",
transforms = list(
list(
type = "filter",
target = ~mesh_grp,
operation = "=",
value = unique(test_data$mesh_grp)[1]
)
)
) %>%
layout(
barmode = "stack",
updatemenus = list(
list(
type = "dropdown",
active = 0,
buttons = list(
list(
method = "restyle",
args = list("transforms[0].value", unique(test_data$mesh_grp)[1]),
label = unique(test_data$mesh_grp)[1]
),
list(
method = "restyle",
args = list("transforms[0].value", unique(test_data$mesh_grp)[2]),
label = unique(test_data$mesh_grp)[2]
)
)
)
)
)
2