我正在尝试使用可绘制的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
答案 0 :(得分:1)
您快到了。条形图(组/堆栈)是一种布局选项,并且不是其他图表类型:
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。