更新按钮不适用于 plotly R 图表

Update buttons not working on plotly R charts

我正在尝试在 plotly r 图表中使用更新按钮,用户可以在其中将图表类型更改为分组或堆叠。组条形图第一次起作用,但堆叠从来没有起作用。下面是我正在使用的代码。

library(plotly)

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

chart_types <- list(
  type = "buttons",
  direction = "right",
  xanchor = 'center',
  yanchor = "top",
  pad = list('r'= 0, 't'= 10, 'b' = 10),
  x = 0.5,
  y = 1.27,
  buttons = list(
        list(method = "restyle",
         args = list("type", "stack"),
         label = "Stack"),
    list(method = "restyle",
         args = list("type", "group"),
         label = "Group")
  ))

p <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
  add_trace(y = ~LA_Zoo, name = 'LA Zoo')%>% layout(updatemenus = list(chart_types))
p 

你快到了。 barmode (group/stack) 是一个布局选项,而不是不同的图表类型:

library(plotly)

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

chart_layouts <- list(
  type = "buttons",
  direction = "right",
  xanchor = 'center',
  yanchor = "top",
  pad = list('r'= 0, 't'= 10, 'b' = 10),
  x = 0.5,
  y = 1.27,
  buttons = list(
    list(method = "relayout",
         args = list("barmode", "stack"),
         label = "Stack"),
    list(method = "relayout",
         args = list("barmode", "group"),
         label = "Group")
  ))

p <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo') %>%
  add_trace(y = ~LA_Zoo, name = 'LA Zoo') %>% layout(updatemenus = list(chart_layouts), barmode="group")
p 

因此您需要使用 relayout 而不是 restyle

详情请见documentation