【发布时间】:2021-05-15 14:22:33
【问题描述】:
我正在使用 R 编程语言。我正在尝试在此处为我自己的数据复制本教程:https://plotly.com/r/dropdowns/
我创建了一些假数据并制作了 4 个图:
#load libraries
library(plotly)
library(MASS)
library(dplyr)
# create data
x <- sample( LETTERS[1:4], 731, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
y <- rnorm(731,10,10)
z <- rnorm(731,5,5)
date= seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
df <- data.frame(x,y, z, date)
df$x = as.factor(df$x)
# plot 1 : time series
aggregate = df %>%
mutate(date = as.Date(date)) %>%
group_by(month = format(date, "%Y-%m")) %>%
summarise( mean = mean(y))
ts_1 <- ggplot(aggregate) + geom_line(aes(x = month, y = mean, group = 1)) + theme(axis.text.x = element_text(angle = 90)) + ggtitle("time series 1")
plot_1 = ggplotly(ts_1)
#plot 2 : box plot
plot_2 <- plot_ly(df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")
#plot 3, 4 : scatter plots
df_1 <- df[which(df$x == "A"),]
df_2 <- df[which(df$x == "B"),]
plot_3 <- plot_ly( data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3")
plot_4 <- plot_ly( data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4")
一旦创建了这 4 个地块,我就知道如何将它们保存在一起:
sub = subplot(plot_1, plot_2, plot_3, plot_4, nrows = 2)
#view result
sub
现在我想做的是让用户在这些图表之间“切换”(切换)(如下所示:https://plotly.com/r/dropdowns/)
在之前的帖子 (R: Switching Between Graphs) 中,我学习了如何将相似的图表“粘合”在一起(例如 4 个散点图)。现在,我正在尝试使用不同的图表(2 个散点图、1 个时间序列和 1 个箱线图)来实现。我尝试修改上一篇文章中的代码以适合我的示例:
fig <- df %>%
add_trace(name = "A", plot_1) %>%
add_trace (name = "B" , df, y = ~y, color = ~x, type = "box") %>% layout(title = "boxplot")
add_trace (name = "C" , data = df_1, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 3") %>%
add_trace( name = "D", data = df_2, type = "scatter", mode = "markers", x = ~ y, y = ~z) %>% layout(title = "graph 4") %>%
layout(xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, FALSE, FALSE, FALSE)),
label = "A"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE, FALSE, FALSE)),
label = "B"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, TRUE, FALSE)),
label = "C"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
label = "D")))))
但这会产生以下错误:
Error: $ operator is invalid for atomic vectors
Error in add_data(p, data) : argument "p" is missing, with no default
有人可以告诉我是否可以解决此问题吗?不是使用"add_trace" 方法,而是以某种方式单独调用每个绘图对象的名称(例如subplot(plot_1, plot_2, plot_3, plot_4, nrows = 2)),将所有图形“粘合”在一起,然后添加一个“切换按钮”,让用户在它们之间切换?
(注意:我需要能够将最终结果保存为“html”文件)
谢谢
【问题讨论】:
-
add_trace需要plot_ly对象,而不是data.frame,这解释了您遇到的错误。 -
谢谢!你能告诉我如何解决这个问题吗?
标签: r dplyr onclick plotly r-plotly