简体   繁体   中英

Display R Shiny Plot After Inputting File

I would like to display a chart (for a Shiny app), based on data inputted by a user through a file. With the current setup, there is an error message claiming the data is not found, so the plot (from the rCharts package) does not get displayed.

Code attached below:

ui.R

library(rCharts)
library(shinydashboard)
library(shiny)
dashboardPage(
  skin = "black",
  header <- dashboardHeader(
    titleWidth = 475
  ),
  sidebar <- dashboardSidebar(
    sidebarMenu(
    )    
  ),
  body <- dashboardBody(
    tabItems(
      tabItem("setup",
              box(width = 4,title = tags$b('Input Dataset'), solidHeader = T, status = 'primary', collapsible = T,
                  helpText("Default max. file size is 5 MB. Please upload both files for analysis in csv format."),
                  fileInput("file1","Upload the first file"),
                  fileInput("file2","Upload the second file")
              ),                  
              box(height = 500, width = 12,title = tags$b('Visualize Data'), solidHeader = T, status = 'primary',
                  showOutput("myPlot", "Highcharts")                  
              )
      )
    )
  )
)

server.R

library(shiny)
library(rCharts)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  observe({
    file1 = input$file1
    file2 = input$file2
    if (is.null(file1) || is.null(file2)) {
      return(NULL)
    }
    data1 = read.csv(file1$datapath)
    data2 = read.csv(file2$datapath)
  })
  output$myPlot<-renderChart2({
    # Prepare data

    data1[,2] <- (data1[,2])/sum(data1[,2])

    # Create chart
    a <- rCharts:::Highcharts$new()
    a$chart(type = "column")
    a$xAxis(categories = rownames(x))
    a$yAxis(title = list(text = "Normalized Intensity"))
    a$data(data1)
    a$set(width = 600, height = 500)
    return(a)
  })
})

Try adding something like this. Make sure you check for nrow and return and empty Highcharts$new() object as renderChart2 expects one.

library(shiny)
library(rCharts)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {

  data1 <- reactive({read.csv(file1$datapath)})
  data2 <- reactive({read.csv(file2$datapath)})

  output$myPlot<-renderChart2({
    data1 <- data1()
    # Prepare data
    if(nrow(data1==0)){return(Highcharts$new())}
    data1[,2] <- (data1[,2])/sum(data1[,2])

    # Create chart
    a <- rCharts:::Highcharts$new()
    a$chart(type = "column")
    a$xAxis(categories = rownames(x))
    a$yAxis(title = list(text = "Normalized Intensity"))
    a$data(data1)
    a$set(width = 600, height = 500)
    return(a)
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM