【发布时间】:2021-05-14 10:34:00
【问题描述】:
我正在使用 R 编程语言。我正在尝试按照此处有关“在图表之间切换”的教程进行操作:https://plotly.com/r/dropdowns/(第一个示例)。
首先,我在 R 中生成了一些数据:
library(plotly)
library(MASS)
x <- sample( LETTERS[1:4], 1000, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
y <- rnorm(1000,10,10)
z <- rnorm(1000,5,5)
df <- data.frame(x,y, z)
df$x = as.factor(df$x)
colnames(df) <- c("x", "y", "z")
我尝试修改本教程中的代码以获得最终结果:
fig <- plot_ly(df, x = ~x, y = ~y, z = ~z alpha = 0.3)
fig <- fig %>% add_markers(marker = list(line = list(color = "black", width = 1)))
fig <- fig %>% layout(
title = "Drop down menus - Plot type",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.8,
buttons = list(
list(method = "restyle",
args = list("type", "scatter"),
label = "Scatter A"),
list(method = "restyle",
args = list("type", "scatter"),
label = "Scatter B"),
list(method = "restyle",
args = list("type", "scatter"),
label = "Scatter C"),
list(method = "restyle",
args = list("type", "scatter"),
label = "Scatter D")
))
但这似乎不起作用。
相反,我有一个不同的想法:也许我可以创建一系列我希望能够在以下之间“切换”的图表:
df_1 <- df[which(df$x == "A"),]
df_2 <- df[which(df$x == "B"),]
df_3 <- df[which(df$x == "C"),]
df_4 <- df[which(df$x == "D"),]
graph_1 <- plot_ly( data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 1")
graph_2 <- plot_ly( data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 2")
graph_3 <- plot_ly( data = df_3, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3")
graph_4 <- plot_ly( data = df_4, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4")
graph_5 <- plot_ly(df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")
现在,是否可以修改 plotly 代码以将所有这些图形(graph_1、graph_2、graph_3、graph_4、graph_5)“绑定”在一起,以便用户可以单击左侧的选项卡并在这些图形之间切换?
谢谢
【问题讨论】:
标签: r onclick plotly data-visualization interactive