How can I plot data in a CSV file after uploading it using R shiny? I have used the code below and seems not working for me


#1

output$salesanalysis<- renderPlot({
attach(get(input$file1))
plot(x=get(input$x), y=get(input$y), xlab = input$x, ylab = input$y)
})


#2

Hi! Welcome! Have you taken a look at the file upload example in the Shiny gallery?

https://shiny.rstudio.com/gallery/file-upload.html

You will need to convert the CSV into a data frame. After that, you can plot it using typical methods. There are lots of examples of plotting in Shiny in the gallery, as well: https://shiny.rstudio.com/gallery/

If you need more specific help, you'll probably need to provide more of your app's code ā€” ideally, a self-contained reproducible example. Some helpful FAQs:



#3
#
# This is the user-interface definition of a Shiny web application. You can
# run the application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
# 
#    http://shiny.rstudio.com/
#
library(shiny)
library(ggplot2)
library(DT)
#library(plotly)
ui <- fluidPage(
  
  # App title ----
  titlePanel("SAMRAT INVENTROY FORECASTING APPLICATION"),
  
  # Sidebar layout with input and output definitions ----
  sidebarLayout(
    
    # Sidebar panel for inputs ----
    sidebarPanel(
      
      #FILE INPUT
      fileInput('file1', 'Choose file to upload',
                accept = c(
                  'text/csv',
                  'text/comma-separated-values',
                  'text/tab-separated-values',
                  'text/plain',
                  '.tsv'
                )
      ),
      
      checkboxInput("header", "Header", TRUE),
      
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head"),
      
      
     
      
      #ploting sales
      selectInput("x", "Select the first X variable:",
                  choices =  c("Sales" = "Sales",
                               "Quantity" = "Quantity",
                               "Discount" = "Discount",
                               "Profit" = "Profit")),
      
      selectInput("y", "Select the first Y variable:",
                  choices =  c("Sales" = "Sales",
                               "Quantity" = "Quantity",
                               "Discount" = "Discount",
                               "Profit" = "Profit")),
      
      #ploting the regression model
      actionButton(inputId = "click3", label = "Plot Regression Model Residuals"),
      hr(),
      #ploting the sales prediction
      actionButton(inputId = "click4", label = "Plot Sales Prediction"),
       hr(),
      
      #predict per product
      selectInput("pre", "Predicting Per Product Category:",
                  choices =  c("Funiture" = "funi",
                               "Office Supplies" = "off",
                               "Technology" = "tech")),
      actionButton(inputId = "click5", label = "Predict"),
      
      
      
      #DISTRIBUTION TYPE
      radioButtons("dist", "TYPE OF GRAPH TO PLOT:",
                   choices = c("BAR GRAPH" = "bar",
                     "HISTOGRAM" = "hist",
                     "BOX PLOT" = "box",
                     "DENSITY" = "density"), selected = "BAR GRAPH"),
      hr(),
      
      # Input: Slider for the number of observations to generate ----
      sliderInput("n",
                  "Number of observations:",
                  value = 500,
                  min = 1,
                  max = 1000)
      
    ),
    
    
    # Main panel for displaying outputs ----
    mainPanel(
      #DT::dataTableOutput('contents'),
      
      # Output: Tabset data, salesanalysis, and predictions ----
      tabsetPanel(type = "tabs",
                  tabPanel(h2('CONTENTS'), dataTableOutput('contents')),
                  tabPanel("Sales Analysis", plotOutput("salesanalysis")),
                  tabPanel("Predictions", plotOutput("predictions"))
                  
      )
      
    )

    )
  
)

#4

#5

HI @vonkuch,

it looks like the code you shared is only the ui portion of your shiny application and that your problem is in your server portion of the code. Can you please share server code too, so that people can better diagnose your problem?

right off the bat, I can tell you that you will need to use either read_delim, read_tsv or read_csv from the readr package (or base R equivalents, if you prefer) to read in the package. I would also move the data import step outside of your output$salesanalysis. You could try this:

data <- reactive({
  if (stringr::str_detect(input$file1, "\\.csv")){
    return(read_csv(input$file1))
  } else if (stringr::str_detect(input$file1, "\\.tsv")){
    return(read_tsv(input$file1))
  } else {
     # add more logic for any other potential input types
  }
})   

output$salesanalysis <- renderPlot({
  plot(data()[input$x], data()[input$y]) 
})


#6

MY ISSUE IS TRYING TO PLOT DATA FROM AND UPLOADED DATASET USING THE FILEUPLOAD AND CREATING A LINEAR MODEL FROM IT USING R SHINY. THIS IS THE SERVER CODE PART. THANK YOU

# This is the server logic of a Shiny web application. You can run the 
# application by clicking 'Run App' above.
#
# Find out more about building applications with Shiny here:
# 
#    http://shiny.rstudio.com/
#

library(shiny)
library(ggplot2)
library(DT)
library(plotly)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  mydata <- reactive({
    
    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.
    
    inFile <- input$file1
    
    if (is.null(inFile))
      return(NULL)
    
    data <-read.csv(inFile$datapath, header = input$header)
    data
    
    #outputing the head or all data only
    if (input$disp == "head") {
      return(head(data))
    }
    else {
      return(data)
    }
  
  
})
  output$contents <- DT::renderDataTable({
    DT::datatable(mydata())       
  })
 
  output$salesanalysis1<-renderText({
    switch(input$dist,
           "box" 	= 	"BOX PLOT",
           "hist" =	"HISTOGRAM",
           "density" 	=	"DENSITY PLOT",
           "bar" 		=	"BAR GRAPH")
  })
 
  
  output$salesanalysis <- renderPlot({
    Plot the table  
    matplot(data[, 1], data[, 2:21],  type="l", main="MATPLOT FOR THE DATASET", xlab="x", ylab="y")    
    grid() 
  })
  
  
  
  
})

#7

I am a little confused about what your issue is. Does the code you posted work currently?

What is your issue regarding the linear model? I am not seeing anything in your code that is creating a linear model to graph. It looks like you are using base graphics so you would have to calculate the linear model using lm and then plot it with abline. Alternatively, if you switched to ggplot2 you could plot your data and use geom_smooth(method = "lm ) as a layer to your plot which will automatically add a linear model. Although, you will need to change the way the rest of your plot is created to do this.

Also, I am not super familiar with base graphics at this point, but do you mean to have 20 columns has your second argument to matplot?