I am looking for some guidance on how to use either facet_grid
or subplot
in my example below. The desired output would be: a grid of individual bar graphs that have the dropdown faceted by the variable "prac". I tried both subplot()
and facet_grid
but haven't yet gotten either to create the appropriate output. Below is how I tried to incorporate the facet_grid()
. Any tips?
library(tidyverse)
library(plotly)
period <- c('201901', '201901', '201904', '201905')
spec <- c('alpha', 'bravo','bravo', 'charlie')
prac <- c('mine','yours','yours','mine')
c <- c(5,6,3,8)
e <- c(1,2,4,5)
df <- data.frame(period, spec,prac, c,e)
spec.val <- unique(df$spec)
ggplot(plot_ly(
df %>% pivot_longer(-c(period, spec, prac)),
x = ~period, y = ~value, color = ~name,
type = "bar",
transforms = list(
list(
type = "filter",
target = ~spec,
operation = "=",
value = spec.val[1]))) %>%
layout(
updatemenus = list(
list(
type = "drowdown",
active = 0,
buttons = map(spec.val, ~list(
method = "restyle",
args = list("transforms[0].value", .x),
label = .x))))) + facet_grid(~prac))
EDIT:
I tried to add a loop to create the multiple plots. This doesnt work, but conceptually I think this could solve my problem. Any ideas on what I am doing wrong? The below doesn't generate any output (or errors).
spec.val <- unique(df$spec)
for (p in unique(df$prac)) {
x <- subset(df, prac == p)
(plot_ly(
df %>% pivot_longer(-c(period, spec, prac)),
x = ~period, y = ~value, color = ~name,
type = "bar",
transforms = list(
list(
type = "filter",
target = ~spec,
operation = "=",
value = spec.val[1]))) %>%
layout(
updatemenus = list(
list(
type = "drowdown",
active = 0,
buttons = map(spec.val, ~list(
method = "restyle",
args = list("transforms[0].value", .x),
label = .x)))))
)
}