Refresh plot on shiny app based on an iteration in server file in R

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Refresh plot on shiny app based on an iteration in server file in R

tej246
I have a requirement to refresh bar chart in UI based on an data in a file.

Sample file:

CCS_DIAGNOSIS_DESCRIPTION,DISCHARGE_YEAR,AGE_GROUP,Number Of Cases,Year_Age_Y
ABDOMINAL HERNIA,2009,0 to 17,425,2009
ABDOMINAL HERNIA,2009,,329,
ABDOMINAL PAIN,2009,0 to 17,966,2009
ABDOMINAL PAIN,2009,,1459,
ui.r:

library(shiny)

shinyUI(fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose file to upload',
                accept = c(
                  'text/csv',
                  'text/comma-separated-values',
                  'text/tab-separated-values',
                  'text/plain',
                  '.csv',
                  '.tsv'
                )
      ),
      tags$hr(),
      checkboxInput('header', 'Header', TRUE),
      radioButtons('sep', 'Separator',
                   c(Comma=',',
                     Semicolon=';',
                     Tab='\t'),
                   ','),
      radioButtons('quote', 'Quote',
                   c(None='',
                     'Double Quote'='"',
                     'Single Quote'="'"),
                   '"'),
      tags$hr(),
      p('If you want a sample .csv or .tsv file to upload,',
        'you can first download the sample',
        a(href = 'mtcars.csv', 'mtcars.csv'), 'or',
        a(href = 'pressure.tsv', 'pressure.tsv'),
        'files, and then try uploading them.'
      )
    ),
    mainPanel(
      plotOutput('distPlot')
    )


  )
)
)
Server.R

library(shiny)


shinyServer(function(input, output) {


  output$distPlot <- renderPlot({

    inputfile <- input$file1

    if (is.null(inputfile))
      return(NULL)

    ds <-read.csv(inputfile$datapath, header = input$header,
                  sep = input$sep, quote = input$quote)
    #print(ds)
    age_grp <- c("0 to 17", "18 to 29", "30 to 49", "50 to 69", "70 or Older")
    colours <- c("red", "orange", "blue", "yellow", "green")
    unq= unique(ds$CCS_DIAGNOSIS_DESCRIPTION,incomparables = FALSE)

    for(val in unq[1:2]){    
      print(val)

      df= ds[ds$CCS_DIAGNOSIS_DESCRIPTION == val ,c("Year_Age_Y","Number.Of.Cases")]

      barplot(df$`Number.Of.Cases`,names.arg = df$Year_Age_Y,ylab=val, col=colours,beside=TRUE,legend = age_grp)
      Sys.sleep(5)
    }
  })


})
When I execute this code, the graph gets plotted only for the last value read from the input. It does go in the the loop and prints the values as desirec ut the plotted chart does not change. It just shows a blank screen for initial iterations and then a graph with late one.