循环 |剧情菜单
Loop | Plotly menu
我有一个数据集,其结构与 Iris 数据集相同,但有 50 多个变量。因此,我想创建一个循环以自动创建菜单。谢谢!
library(plotly)
p <- iris %>%
plot_ly(
type = 'scatter',
x = ~Sepal.Length,
y = ~Petal.Length,
text = ~Species,
hoverinfo = 'text',
mode = 'markers',
transforms = list(
list(
type = 'filter',
target = ~Species,
operation = '=',
value = unique(iris$Species)[1]
)
)) %>% layout(
updatemenus = list(
list(
type = 'dropdown',
active = 0,
buttons = list(
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[1]),
label = unique(iris$Species)[1]),
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[2]),
label = unique(iris$Species)[2]),
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[3]),
label = unique(iris$Species)[3])
)
)
)
)
p
该函数遍历菜单项的数量,并以绘图要求的格式为每个菜单项创建一个按钮。
library(plotly)
get_menu_list <- function(names){
n_names = length(names)
buttons = vector("list",n_names)
for(i in seq_along(buttons)){
buttons[i] = list(list(method = "restyle",
args = list("transforms[0].value", names[i]),
label = names[i]))
}
return_list = list(
list(
type = 'dropdown',
active = 0,
buttons = buttons
)
)
return(return_list)
}
p <- iris %>%
plot_ly(
type = 'scatter',
x = ~Sepal.Length,
y = ~Petal.Length,
text = ~Species,
hoverinfo = 'text',
mode = 'markers',
transforms = list(
list(
type = 'filter',
target = ~Species,
operation = '=',
value = unique(iris$Species)[1]
)
)) %>% layout(
updatemenus = get_menu_list(unique(iris$Species))
)
我有一个数据集,其结构与 Iris 数据集相同,但有 50 多个变量。因此,我想创建一个循环以自动创建菜单。谢谢!
library(plotly)
p <- iris %>%
plot_ly(
type = 'scatter',
x = ~Sepal.Length,
y = ~Petal.Length,
text = ~Species,
hoverinfo = 'text',
mode = 'markers',
transforms = list(
list(
type = 'filter',
target = ~Species,
operation = '=',
value = unique(iris$Species)[1]
)
)) %>% layout(
updatemenus = list(
list(
type = 'dropdown',
active = 0,
buttons = list(
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[1]),
label = unique(iris$Species)[1]),
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[2]),
label = unique(iris$Species)[2]),
list(method = "restyle",
args = list("transforms[0].value", unique(iris$Species)[3]),
label = unique(iris$Species)[3])
)
)
)
)
p
该函数遍历菜单项的数量,并以绘图要求的格式为每个菜单项创建一个按钮。
library(plotly)
get_menu_list <- function(names){
n_names = length(names)
buttons = vector("list",n_names)
for(i in seq_along(buttons)){
buttons[i] = list(list(method = "restyle",
args = list("transforms[0].value", names[i]),
label = names[i]))
}
return_list = list(
list(
type = 'dropdown',
active = 0,
buttons = buttons
)
)
return(return_list)
}
p <- iris %>%
plot_ly(
type = 'scatter',
x = ~Sepal.Length,
y = ~Petal.Length,
text = ~Species,
hoverinfo = 'text',
mode = 'markers',
transforms = list(
list(
type = 'filter',
target = ~Species,
operation = '=',
value = unique(iris$Species)[1]
)
)) %>% layout(
updatemenus = get_menu_list(unique(iris$Species))
)