0

Could anyone suggest me the way to extract shiny checkboxgroupoinput options of different ggplots such as geom_bar(), geom_line() as a list. I tried the following simplified code, it prints only the last plot: Thanks for your help.

 library(shiny)
  library(ggplot2)
  library(easyGgplot2)
  patient <- cbind.data.frame(seq(1:14),matrix(sample(1:100, 84), ncol=6))
 colnames(patient) <- c('DAYS', 'PHYSICAL_ACTIVITY', 'SMOKING','ALCOHOL_INTAKE', 'HYDRATION', 'SLEEP', 'Total_score')
    ui <- fluidPage(
                titlePanel("Data Plot"),
                        sidebarLayout(
                                sidebarPanel(
                        fluidRow(column(6, 
                                    checkboxGroupInput("checkGroup", 
                                      ("Parameters"), 
                                    list("PHYSICAL ACTIVITY" = 1, 
                                       "SLEEP" = 2, 
                                      "ALCOHOL INTAKE" = 3,
                                      "SELECT ALL" = 4
                                        )))
                                      ),
                       fluidRow(column(10, actionButton("goButton", label = "Analysis Report"))
                                            )
                                          ), #Sidebarpanel
                                                    mainPanel(
                                                        plotOutput("plot1", height='800px')

                                        )#Mainpanel
                      ) #Sidebar layout
        )#fluidpage

 server <- function(input, output) {
 output$plot1 <- renderPlot({ 
 input$goButton
  p1 <- reactive({
    if(!(1 %in% input$checkGroup)) return(NULL)
      ggplot(data=patient, aes(x=DAYS, y=PHYSICAL_ACTIVITY))+geom_bar(stat="identity", aes(fill=PHYSICAL_ACTIVITY<=median(PHYSICAL_ACTIVITY)), show.legend=F)+scale_fill_manual(values = c('steelblue', 'red') )+labs(title = 'PHYSICAL ACTIVITY (STEPS)', x = NULL, y = NULL)+theme_minimal()
   })
  # Second plot
  p2 <- reactive ({
      if(!(2 %in% input$checkGroup )) return(NULL)
      p2 <- ggplot(data=patient, aes(x=DAYS,y=SLEEP))+geom_line(colour='black', size=1)+geom_point(size=3, aes(colour=cut(SLEEP,c(-Inf,summary(SLEEP)[[2]],summary(SLEEP)[[5]],Inf))), show.legend=F)+scale_color_manual(values = c("red", "orange","green"))+labs(title = 'SLEEP (hrs)', x = NULL, y = NULL) +theme_minimal() 
  })
  ptlist <- list(p1(),p2())
  ggplot2.multiplot(ptlist, cols=1)
 })
 }
shinyApp(ui, server)
aosmith
  • 34,856
  • 9
  • 84
  • 118
Eddie S
  • 5
  • 1
  • 4
  • It is really unclear to me what you are trying to achieve. Could you please elaborate? See [here](https://stackoverflow.com/help/how-to-ask) for tips on how to ask a good question and [here](https://stackoverflow.com/questions/48343080/how-to-convert-a-shiny-app-consisting-of-multiple-files-into-an-easily-shareable/48343110#48343110) for tips on how to create a reproducible example. – Florian Jul 09 '18 at 08:29
  • Thanks @Florian , I edited a reproducible example with simplified ui page. I would like to plot the ggplot objects (bar and line plots) in the main panel as per the user options from checkboxGroupInput. I need to stack the plots (different types) in one column (horizontal stacking) – Eddie S Jul 09 '18 at 09:07
  • The way you currently have `reactives` in your `renderPlot` looks strange to me. All the code in `renderPlot` will be invalidated anyway when one of the reactive elements in its body changes. Seems like you want to have a dynamic number of plots, based on the users choices? Maybe [this](https://stackoverflow.com/questions/15875786/dynamically-add-plots-to-web-page-using-shiny) helps. – Florian Jul 09 '18 at 11:49
  • Thanks @Florian for your suggested post. In fact, I don’t intend to get a dynamic number of plots. Considering the checkbox options (ex: physical activity , sleep, all) the action button (goButton) should take the inputs from checkGroup and display the ‘n’ plots in the main panel. In such cases, reactive are not needed? Plz suggest me a way to do that. Thanks. – Eddie S Jul 09 '18 at 14:26

3 Answers3

0

It will work if replace ggplot2.multiplot(ptlist, cols=1) by do.call(ggplot2.multiplot, c(ptlist, cols=1))

But may be to do this with ggplot function in reactive is not a good way to achieve your goal. You could to try something like this

library(shiny)
library(ggplot2)
library(easyGgplot2)

patient <- cbind.data.frame(
    seq(1:14), 
    matrix(
        sample(1:100, 84), 
        ncol = 6
    )
)

colnames(patient) <- c(
    'DAYS',
    'PHYSICAL_ACTIVITY',
    'SMOKING',
    'ALCOHOL_INTAKE',
    'HYDRATION',
    'SLEEP',
    'Total_score'
)

ui <- fluidPage(
    titlePanel("Data Plot"),
    sidebarLayout(
        sidebarPanel(
            fluidRow(
                column(6,
                       checkboxGroupInput(
                           "checkGroup",
                           "Parameters",
                           list(
                               "PHYSICAL ACTIVITY",
                               "SLEEP"),
                           selected = "PHYSICAL ACTIVITY")
                       )
                )
            ),
        mainPanel(
            plotOutput("plots")
        )
    )
)

server <- function(input, output) {

    plot_one <- ggplot(data = patient, aes(x = DAYS, y = PHYSICAL_ACTIVITY)) + 
        geom_bar(
            stat = "identity",
            aes(fill = PHYSICAL_ACTIVITY <= median(PHYSICAL_ACTIVITY)),
            show.legend = F) + 
        scale_fill_manual(
            values = c('steelblue', 'red')) + 
        labs(title = 'PHYSICAL ACTIVITY (STEPS)',
             x = NULL,
             y = NULL) + 
        theme_minimal()

    plot_two <- ggplot(data = patient, aes(x = DAYS, y = SLEEP)) + 
        geom_line(colour = 'black', size = 1) + 
        geom_point(size = 3, 
                   aes(colour = cut(SLEEP, 
                                    c(-Inf, 
                                      summary(SLEEP)[[2]], 
                                      summary(SLEEP)[[5]], 
                                      Inf)
                                )
                   ),
                   show.legend = F) + 
        scale_color_manual(values = c("red", "orange", "green")) + 
        labs(title = 'SLEEP (hrs)', 
             x = NULL,
             y = NULL) + 
        theme_minimal()

    list.of.plots <- list(
        `PHYSICAL ACTIVITY` = plot_one,
        `SLEEP` = plot_two
    )

    output$plots <- renderPlot(
        do.call(ggplot2.multiplot, c(list.of.plots[input$checkGroup], cols=1))
    )

}
shinyApp(ui, server)
  • This is perfect, Thanks @epam employee – Eddie S Jul 09 '18 at 21:27
  • Would it be possible to add a reactive for read.csv to accept the local data in your server code? I tried, but getting reactive context errors when I call using plot_one <- ggplot(patient(), aes()) Thanks for your suggestions – Eddie S Jul 10 '18 at 09:53
  • @EddieS you are welcome! Yes, you can add reactive with reading but in your example below you try use **reactive** out of any **reactive context** Below I gave an example of how to achieve your purpose – epam employee Jul 11 '18 at 10:26
  • @EddieS One the future, please. try to ask one question at a time. Because title of your question is **shiny checkboxGroupInput ggplots as list** but now you also ask about **reactive** and **fileInput** – epam employee Jul 11 '18 at 10:36
  • Thanks, loads @epam, Now I understood. I apologize for the additional question in this thread. I stick to the suggested way of creating a separate question specific to the title. – Eddie S Jul 11 '18 at 14:18
0
        library(shiny)
        library(ggplot2)
        library(easyGgplot2)
        patient <- cbind.data.frame(
          seq(1:14), 
          matrix(
            sample(1:100, 84), 
            ncol = 6
          )
        )
        colnames(patient) <- c(
          'DAYS',
          'PHYSICAL_ACTIVITY',
          'SMOKING',
          'ALCOHOL_INTAKE',
          'HYDRATION',
          'SLEEP',
          'Total_score'
        )
        write.csv(patient, file="patient.csv")
        ui <- fluidPage(
          titlePanel("Data Plot"),
          sidebarLayout(
            sidebarPanel(
              fluidRow(
                column(6,
                       checkboxGroupInput(
                         "checkGroup",
                         "Parameters",
                         list(
                           "PHYSICAL ACTIVITY",
                           "SLEEP"),
                         selected = "PHYSICAL ACTIVITY")
                )
              ),
              fluidRow(
                fileInput("file1", "Choose Data sheet",
                          multiple = TRUE,
                          accept = c("text/csv",
                                     "text/comma-separated-values,text/plain",
                                     ".csv"))
              )
            ),
            mainPanel(
              plotOutput("plots")
            )
          )
        )
        server <- function(input, output) {
          patient <- reactive({
            req(input$file1)
            read.csv(input$file1$datapath,
                     header = T
                     )   
          })
          plot_one <- ggplot(data = patient(), aes(x = DAYS, y = PHYSICAL_ACTIVITY)) + 
            geom_bar(
              stat = "identity",
              aes(fill = PHYSICAL_ACTIVITY <= median(PHYSICAL_ACTIVITY)),
              show.legend = F) + 
            scale_fill_manual(
              values = c('steelblue', 'red')) + 
            labs(title = 'PHYSICAL ACTIVITY (STEPS)',
                 x = NULL,
                 y = NULL) + 
            theme_minimal()
          plot_two <- ggplot(data = patient(), aes(x = DAYS, y = SLEEP)) + 
            geom_line(colour = 'black', size = 1) + 
            geom_point(size = 3, 
                       aes(colour = cut(SLEEP, 
                                        c(-Inf, 
                                          summary(SLEEP)[[2]], 
                                          summary(SLEEP)[[5]], 
                                          Inf)
                       )
                       ),
                       show.legend = F) + 
            scale_color_manual(values = c("red", "orange", "green")) + 
            labs(title = 'SLEEP (hrs)', 
                 x = NULL,
                 y = NULL) + 
            theme_minimal()
        list.of.plots <- list(
            `PHYSICAL ACTIVITY` = plot_one,
            `SLEEP` = plot_two
          )
        output$plots <- renderPlot(
            do.call(ggplot2.multiplot, c(list.of.plots[input$checkGroup], cols=1))
          )
        }
        shinyApp(ui, server)
Eddie S
  • 5
  • 1
  • 4
0

Example with reading csv.

library(shiny)
library(ggplot2)
library(easyGgplot2)
patient <- cbind.data.frame(
    seq(1:14), 
    matrix(
        sample(1:100, 84), 
        ncol = 6
    )
)
colnames(patient) <- c(
    'DAYS',
    'PHYSICAL_ACTIVITY',
    'SMOKING',
    'ALCOHOL_INTAKE',
    'HYDRATION',
    'SLEEP',
    'Total_score'
)
write.csv(patient, file="patient.csv")
ui <- fluidPage(
    titlePanel("Data Plot"),
    sidebarLayout(
        sidebarPanel(
            fluidRow(
                column(6,
                       checkboxGroupInput(
                           "checkGroup",
                           "Parameters",
                           list(
                               "PHYSICAL ACTIVITY",
                               "SLEEP"),
                           selected = "PHYSICAL ACTIVITY")
                )
            ),
            fluidRow(
                fileInput("file1", "Choose Data sheet",
                          multiple = TRUE,
                          accept = c("text/csv",
                                     "text/comma-separated-values,text/plain",
                                     ".csv"))
            )
        ),
        mainPanel(
            plotOutput("plots")
        )
    )
)
server <- function(input, output) {
    patient <- reactive({
        req(input$file1)
        read.csv(input$file1$datapath,
                 header = T
        )   
    })
    plot_one <- function(patient.data) {
        ggplot(patient.data, aes(x = DAYS, y = PHYSICAL_ACTIVITY)) + 
            geom_bar(
                stat = "identity",
                aes(fill = PHYSICAL_ACTIVITY <= median(PHYSICAL_ACTIVITY)),
                show.legend = F) + 
            scale_fill_manual(
                values = c('steelblue', 'red')) + 
            labs(title = 'PHYSICAL ACTIVITY (STEPS)',
                 x = NULL,
                 y = NULL) + 
            theme_minimal()
    }
    plot_two <- function(patient.data){
        ggplot(patient.data, aes(x = DAYS, y = SLEEP)) + 
            geom_line(colour = 'black', size = 1) + 
            geom_point(size = 3, 
                       aes(colour = cut(SLEEP, 
                                        c(-Inf, 
                                          summary(SLEEP)[[2]], 
                                          summary(SLEEP)[[5]], 
                                          Inf)
                       )
                       ),
                       show.legend = F) + 
            scale_color_manual(values = c("red", "orange", "green")) + 
            labs(title = 'SLEEP (hrs)', 
                 x = NULL,
                 y = NULL) + 
            theme_minimal()
    }
    output$plots <- renderPlot({
        list.of.plots <- list(
            `PHYSICAL ACTIVITY` = plot_one(patient()),
            `SLEEP` = plot_two(patient())
        )

        do.call(ggplot2.multiplot, c(list.of.plots[input$checkGroup], cols=1))
    })
}
shinyApp(ui, server)