0
votes

I am attempting to write a function that presents the user multiple plots in a specific order created using plotly. The user is meant to see a plot and then when enter is pressed the next plot is to appear. Here is a sample function to illustrate the problem:

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")
}

When test_function() is executed, only the last plot is shown. What can be done to solve the problem?

1

1 Answers

0
votes

As you noticed only the last plot is returned from your function so it is the only one that is printed.

You could just embed both plotly calls within 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"))

But a better practice would be to return the plots from the function for example using list and organize your function like this :

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())