r - Plotly:使用 R 更新参数中的多个数据属性
问题描述
这是@klopetx对这个答案的后续问题。我在官方文档的 Plotly 中搜索了如何更新单个 arg 中的多个数据属性。它在 Python 中是可能的,因此在 Javascript 中也是可能的。为了重现性,我复制了代码示例1。
args = list('y', list(df[, var_name]))
例如,我想让x
. 我通过以下方式对此进行了想象:
args = list('y', list(df[, var_name]),'x', list(df[, var_name]))
添加到代码示例中,这将是:
library(plotly)
df <- data.frame(x = runif(200), y = runif(200), z = runif(200), j = runif(200), k = rep(0.7, 200), i = rnorm(200,0.6,0.05))
create_buttons <- function(df, y_axis_var_names) {
lapply(
y_axis_var_names,
FUN = function(var_name, df) {
button <- list(
method = 'restyle',
# args = list('y', list(df[, var_name])), #previous example for only one attribute
args = list('y', list(df[, var_name]),'x', list(df[, var_name])), #new code which doesn't work
label = sprintf('Show %s', var_name)
)
},
df
)
}
y_axis_var_names <- c('y', 'z', 'j', 'k', 'i')
p <- plot_ly(df, x = ~x, y = ~y, mode = "markers", name = "A", visible = T) %>%
layout(
title = "Drop down menus - Styling",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = create_buttons(df, y_axis_var_names)
)
))
p
解决方案
解决方案来自这个答案:只需将属性包装在一个附加的list()
. 当然,这是直截了当的,但对我来说并不直观。
现在该示例适用于arg
允许添加多个属性的新行。
library(plotly)
df <- data.frame(x = runif(200), y = runif(200), z = runif(200), j = runif(200), k = rep(0.7, 200), i = rnorm(200,0.6,0.05))
create_buttons <- function(df, y_axis_var_names) {
lapply(
y_axis_var_names,
FUN = function(var_name, df) {
button <- list(
method = 'restyle',
# args = list('y', list(df[, var_name])), #previous example for only one attribute
# args = list('y', list(df[, var_name]),'x', list(df[, var_name])), #new code which didn't work
args = list(list(y = list(df[, var_name]),x = list(df[, var_name]))), # working code!
label = sprintf('Show %s', var_name)
)
},
df
)
}
y_axis_var_names <- c('y', 'z', 'j', 'k', 'i')
p <- plot_ly(df, x = ~x, y = ~y, mode = "markers", name = "A", visible = T) %>%
layout(
title = "Drop down menus - Styling",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = create_buttons(df, y_axis_var_names)
)
))
p
推荐阅读
- reactjs - 与 TypeScript 反应的 onKeyDown 事件
- electron - 如何加密 ASAR 档案?
- python - 如何在 matplotlib 中使用 clabels 为轮廓线多次打印标签?
- javascript - 如何确定像素的颜色或色调对应于某种颜色的度数范围?
- docker - 是否可以从 Dockerfile 中指定构建选项来控制构建过程?
- node.js - nodejs express res.send 以完整路径为名称下载文件
- php - 在 Laravel 中单击提交时重复的表单验证错误
- ios - 为什么应用程序在发布模式下显示白屏?
- javascript - 如何在 Django 中使用 JavaScript 获取图表的值?
- svg - SVG d3 中带阴影的箭头标记