Вы можете сделать два отдельных графика и объединить их с subplot
:
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)
df.m <- dplyr::filter(df, prac=="mine") %>% pivot_longer(-c(period, spec, prac))
df.y <- dplyr::filter(df, prac=="yours") %>% pivot_longer(-c(period, spec, prac))
p1 <- plot_ly(
df.m,
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)))))
p2 <- plot_ly(
df.y,
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)))))
subplot(p1, p2)
Смотрите здесь, чтобы узнать больше: Сюжет в r с сюжетом
Редактировать: В более общем плане вы можете создать список графиков и графиков, используя субплот:
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)
getPlots <- function(x){
df.m <- dplyr::filter(df, prac==x) %>% pivot_longer(-c(period, spec, prac))
plot_ly(
df.m,
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)))))
}
plotlist <- lapply(levels(df$prac), getPlots)
subplot(plotlist)