Search code examples
rshinyecharts4r

Render echart from uploading a csv file


I'm trying to make an app that will render you a graph from uploading a csv file to it, in which you can choose the variables to graph. The truth is I don't know what I'm doing wrong, since the app doesn't render the graph. Any ideas or suggestions?

The code is:

library(shiny)
library(echarts4r)

ui <- fluidPage(
  
  selectInput('mydropdown', label = 'Selección de variables', choices = 'Aún no hay variables a escoger'),
  selectInput('mydropdown1', label = 'Selección de variables', choices = 'Aún no hay variables a escoger'),
  fileInput('myfileinput', label = 'Archivo a usar', accept = c(".csv")),
  echarts4rOutput("plot")

)

   #Server
   server <- function(input, output, session) {
  
   observeEvent(input$myfileinput, {
    
    mytable <- read.csv(input$myfileinput$datapath)
    
    updateSelectInput(session, "mydropdown", label = "Select", choices = colnames(mytable))
    updateSelectInput(session, "mydropdown1", label = "Select", choices = colnames(mytable))
    
  })
  
  mytable <- renderEcharts4r({
    myfileinput |> 
      e_charts(input$mydropdown)  |> 
      e_line(input$mydropdown1)
  })
}
shinyApp(ui, server)

Solution

  • There are few syntax errors in the code as well as few logical errors.

    1. You should store the data in a reactive object which can be used anywhere in the app.

    2. The plot should be saved in output$plot corresponding to echarts4rOutput("plot").

    3. Since you are passing character values of column names to echarts use the functions e_charts_ and e_line_.

    Try the following -

    library(shiny)
    library(echarts4r)
    
    ui <- fluidPage(
      
      selectInput('mydropdown', label = 'Selección de variables', choices = 'Aún no hay variables a escoger'),
      selectInput('mydropdown1', label = 'Selección de variables', choices = 'Aún no hay variables a escoger'),
      fileInput('myfileinput', label = 'Archivo a usar', accept = c(".csv")),
      echarts4rOutput("plot")
      
    )
    
    #Server
    server <- function(input, output, session) {
      
      rv <- reactiveValues()
      
      observeEvent(input$myfileinput, {
        
        rv$mytable <- read.csv(input$myfileinput$datapath)
        
        updateSelectInput(session, "mydropdown", label = "Select", choices = colnames(rv$mytable))
        updateSelectInput(session, "mydropdown1", label = "Select", choices = colnames(rv$mytable))
        
      })
      
      output$plot <- renderEcharts4r({
        req(rv$mytable)
        rv$mytable |> 
          e_charts_(input$mydropdown)  |> 
          e_line_(input$mydropdown1)
      })
    }
    
    shinyApp(ui, server)