【发布时间】:2022-08-20 03:55:37
【问题描述】:
我正在尝试根据data.frame 中的一个组生成一系列小的plotly 图,然后使用plotly::subplot() 将它们绑定在一起。然后我想使用dropdown 过滤器只显示一些子图。
到目前为止(使用 plotly 文档https://plotly.com/r/map-subplots-and-small-multiples/ 和这个答案https://stackoverflow.com/a/66205810/1498485)我可以创建图和按钮,并显示和隐藏子图的内容。
但我无法弄清楚如何隐藏/重置轴,因此只显示选定的子图。下面是我正在做的一个最小化的例子。
# create data
df <- expand.grid(group = LETTERS[1:4],
type = factor(c(\'high\',\'med\',\'low\'), levels = c(\'high\',\'med\',\'low\')),
date = seq(as.Date(\'2020-01-01\'), Sys.Date(), \'month\')) %>%
mutate(value = abs(rnorm(nrow(.)))) %>%
group_by(group)
# define plot function
create_plots <- function(dat){
legend <- unique(dat$group) == \'A\'
plot_ly(dat, x = ~date) |>
add_lines(y = ~value, color = ~type, legendgroup = ~type, showlegend = legend) %>%
add_annotations(
text = ~unique(group),
x = 0.1,
y = 0.9,
yref = \"paper\",
xref = \"paper\",
xanchor = \"middle\",
yanchor = \"top\",
showarrow = FALSE,
font = list(size = 15)
)
}
# create buttons to filter by group (based on https://stackoverflow.com/a/66205810/1498485)
buttons <- LETTERS[1:4] |>
lapply(function(x){
list(label = x,
method = \'update\',
args = list(list(
name = c(\'high\', \'med\', \'low\'),
visible = unlist(Map(rep, x == LETTERS[1:4], each = 3))
)))
})
# generate subplots
df %>%
do(mafig = create_plots(.)) %>%
subplot(nrows = 2) %>%
layout(
updatemenus = list(
list(y = 0.8,
buttons = buttons))
)
标签: r plotly interactive subplot r-plotly