首页 > 解决方案 > 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

标签: rr-plotly

解决方案


解决方案来自这个答案:只需将属性包装在一个附加的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

推荐阅读