我一直试图创建一个plotly对象,使用按钮在两个图形之间切换。然而,当我单击按钮时出现的图例和值不是我所期望的。我一直使用以下指南作为参考:
Dropdowns
Custom buttons
以下是我使用的数据示例:
library(plotly)
library(RColorBrewer)
# Create MWE dataframe
set.seed(32)
ae_data <- data.frame(
Program = rep(c("Biology", "Math", "History", "English", "Computer Science",
"Chemistry", "Business", "Philosophy", "Psychology", "Physics"), 5),
Year = rep(2018:2022, each = 10),
Application = round(runif(50, min = 100, max = 900), digits = 0),
Enrolment = round(runif(50, min = 150, max = 950), digits = 0)
)
下面是我用来生成图表的代码:
# Generate the appropriate number of colors
graph_colors <- colorRampPalette(brewer.pal(8, "Set2"))(length(unique(ae_data$Program)))
# Create graph
ae_data %>%
plot_ly(
type = "scatter",
mode = "lines + markers",
colors = graph_colors
) %>%
add_trace(
x = ~Year,
y = ~Application,
color = ~Program
) %>%
add_trace(
x = ~Year,
y = ~Enrolment,
color = ~Program,
visible = F
) %>%
layout(
updatemenus = list(
list(
type = "buttons",
buttons = list(
list(
label = "Application",
method = "update",
args = list(list(visible = c(F, T)),
list(yaxis = list(title = "Application")))
),
list(
label = "Enrolment",
method = "update",
args = list(list(visible = c(T, F)),
list(yaxis = list(title = "Enrolment")))
)
)
)
)
)
最后发生的是,当我点击其中一个按钮时,我的Application和Enrolment帧的图例和值会混淆。我点击每个按钮时会得到一半的Application和Enrolment帧。我希望按钮能够根据updatemenus的参数在上面的跟踪中识别的帧之间切换。我尝试使用其他“方法”输入,但根据文档,“更新”似乎是正确的。
下面是一些图像来说明我的预期值和实际值:
应用程序的预期图表:
点击应用程序的实际图表:
1条答案
按热度按时间huus2vyu1#
一个可能的解决方案是使用Plotly中的update_layout()函数更新图表的布局。具体来说,您可以使用图例参数指定数据更新时图例的行为。请尝试以下代码: