user3022875
user3022875

Reputation: 9018

Shiny R - Print multiple plots using a loop

I have a function in my global.R file that creates a plot:

CreatePlot<-function(mergedFiles,File1, File2) 
{
  main<- mergedFiles
  csv1<- main[,1:4]
  csv2<- cbind( main[,1],main[,5:7] )
  strikes<- factor(main$Strike,levels=c(main$Strike),ordered=TRUE)
  stacked<- stacked <- data.frame(time=strikes, value =c(c(csv1$Vol), c(csv2$Vol)) ,     variable = rep(c(File1,File2), each=NROW(csv1[,1])))  

  g<- ggplot(stacked, aes( x = time,  y=value, colour=variable, group= variable)      )       +   geom_line()  +  xlab("Strike") +geom_point(shape = 7,size = 1) +
    ylab("Volatiltiy") +ggtitle("Plot of Volatilities") + theme(axis.text.x =       element_text(angle = 90, hjust = 1))
  return(g)  
}

I want to create a function to print multiple plots in a loop. Let's say I want 3 plots I am doing something like this in my server.R:

  output$MyList <- renderUI({ 
        main<- mergedFiles() # this is the data for my plots
        g<-CreatePlot(main, input$File1, input$File2) #this calls the create plot function
        for (i in 1:3){
          renderPlot({
              print(g) #for testing purposes I am just trying to print the same plot 3     times
          })
        }

})

and my UI.R in the mainPanel:

uiOutput("MyList")

When I run this nothing happens. The screen is just blank with no errors. Any ides how to print multiple plots like this using a loop?

Thank yoU!

Upvotes: 3

Views: 5263

Answers (1)

Julien Navarre
Julien Navarre

Reputation: 7830

You can't render a plot with renderUI. renderUI evaluates only "expression that returns a Shiny tag object, HTML, or a list of such objects."

You must create a plotOutput for each plot you want to display. So you can create severals plotOuputs dynamically with renderUI and then create the graphs with a loop.

Have a look to this example : https://gist.github.com/wch/5436415/

Upvotes: 3

Related Questions