在 R 中使用 plotly (plot.ly) 创建多个绘图
Create multiple plots using plotly (plot.ly) in R
我正在尝试编写一个函数,以使用 plotly 创建的特定顺序向用户显示多个图。用户应该看到一个图,然后当按下回车键时,下一个图就会出现。
这是一个示例函数来说明问题:
library(plotly)
test_function <- function(){
set.seed(100)
n<-100
x1 <- runif(n)
y1 <- runif(n)
x2 <- runif(n,1,3)
y2 <- runif(n,1,3)
plot_ly(x= ~x1,y= ~y1,type = "scatter")
cat("Hit <Return> to see next plot: ")
line <- readline()
plot_ly(x= ~x2, y= ~y2, type = "scatter")
}
执行test_function()时,只显示最后一个图。
可以做些什么来解决这个问题?
如您所见,只有最后一个图是从您的函数中 return 编辑的,因此它是唯一打印的图。
您可以将两个 plotly
调用嵌入 print
:
print(plot_ly(x= ~x1,y= ~y1,type = "scatter"))
cat("Hit <Return> to see next plot: ")
line <- readline()
print(plot_ly(x= ~x2, y= ~y2, type = "scatter"))
但更好的做法是 return 来自函数的绘图,例如使用 list
并像这样组织您的函数:
test_function <- function(){
set.seed(100)
n<-100
x1 <- runif(n)
y1 <- runif(n)
x2 <- runif(n,1,3)
y2 <- runif(n,1,3)
p1 <- plot_ly(x= ~x1,y= ~y1,type = "scatter")
p2 <- plot_ly(x= ~x2, y= ~y2, type = "scatter")
list(p1,p2) # return the pair of plot
}
show_plots <- function(l){
print(l[[1]]) # display plot 1
cat("Hit <Return> to see next plot: ")
line <- readline()
print(l[[2]]) # display plot 2
}
show_plots(test_function())
我正在尝试编写一个函数,以使用 plotly 创建的特定顺序向用户显示多个图。用户应该看到一个图,然后当按下回车键时,下一个图就会出现。 这是一个示例函数来说明问题:
library(plotly)
test_function <- function(){
set.seed(100)
n<-100
x1 <- runif(n)
y1 <- runif(n)
x2 <- runif(n,1,3)
y2 <- runif(n,1,3)
plot_ly(x= ~x1,y= ~y1,type = "scatter")
cat("Hit <Return> to see next plot: ")
line <- readline()
plot_ly(x= ~x2, y= ~y2, type = "scatter")
}
执行test_function()时,只显示最后一个图。 可以做些什么来解决这个问题?
如您所见,只有最后一个图是从您的函数中 return 编辑的,因此它是唯一打印的图。
您可以将两个 plotly
调用嵌入 print
:
print(plot_ly(x= ~x1,y= ~y1,type = "scatter"))
cat("Hit <Return> to see next plot: ")
line <- readline()
print(plot_ly(x= ~x2, y= ~y2, type = "scatter"))
但更好的做法是 return 来自函数的绘图,例如使用 list
并像这样组织您的函数:
test_function <- function(){
set.seed(100)
n<-100
x1 <- runif(n)
y1 <- runif(n)
x2 <- runif(n,1,3)
y2 <- runif(n,1,3)
p1 <- plot_ly(x= ~x1,y= ~y1,type = "scatter")
p2 <- plot_ly(x= ~x2, y= ~y2, type = "scatter")
list(p1,p2) # return the pair of plot
}
show_plots <- function(l){
print(l[[1]]) # display plot 1
cat("Hit <Return> to see next plot: ")
line <- readline()
print(l[[2]]) # display plot 2
}
show_plots(test_function())