Problem with Bar plot in Shiny app

Please, can someone help me with my app? I am developing an app that calculates financial ratios. I want a situation whereby the user can decide what number of years to analyze comparatively, without having to rigidly stick to the standard five years built in the app i.e. users can choose to analyze financial performance over two years, four years, or three years. Below is my code:

if(interactive()){
library(shiny)
library(shinyalert)  
library(shinycssloaders)  
library(shinythemes)
library(shinyWidgets)
library(SentimentAnalysis)
library(textclean)
library(reactable)
library(tm)  

options(spinner.color="#3498db",
        spinner.color.background="#ffffff",
        spinner.size=1)  
   
ui<-navbarPage(strong("Mavis Analytic"),theme=shinytheme("cerulean"),
               windowTitle="Mavis Analytic",fluid=TRUE,inverse=FALSE,
               tabPanel(strong("Opinion Miner"),icon=icon("table"),useShinyalert(),
                setBackgroundColor("white"),setBackgroundImage(src="white.jpg"),        
                          sidebarLayout(
                          sidebarPanel(width=3,
                          img(src="logo.jpg",height=130,width=150),
                          h4(strong("Enter your texts in these fields")),
                          actionButton("clear",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                          textAreaInput("text","Text Field 1",value="It is a beautiful day"),
                          textAreaInput("texts","Text Field 2",value="I am happy to be here"),
                          textAreaInput("word","Text Field 3",value="Let's have some fun"),
                          textAreaInput("words","Text Field 4",value="It has been a bad outing"),
                          textAreaInput("wordy","Text Field 5",value="I dislike clowns"),
                          actionButton("run",strong("Run Analysis"),icon=icon("caret-right")),br(),hr(),h5(strong("The number of words entered into each text field:")),reactableOutput("count",width="40%"),h5("Designed and developed by Mavis Naissance Consulting"),img(src="New.jpg",height=70,width=70)),
                          mainPanel(h4("The Opinion Miner is a tool for conducting sentiment analysis. It is useful for analyzing and scoring the kinds of sentiments expressed in texts, such as in literature, social media posts, or product reviews."),hr(),h3(strong("Table of Sentiment Scores")),withSpinner(reactableOutput("table"),type=1),downloadButton("download",strong("Download Table")),br(),br(),
                                    column(4,selectInput("choice","Select Sentiment Score to Plot",choices=c("QDAP","LoughranM","HarvardIV"))),column(4,selectInput("color","Select Color",choices=c("Blue","Red","Green","Yellow","Purple"))),
                                    fluidRow(column(6,withSpinner(plotOutput("plot",height=350,width=400),type=1)),column(6,withSpinner(plotOutput("graph",height=350,width=400),type=1))),
                                    fluidRow(column(6,downloadButton("plot.down",strong("Download Graph"))))))),
               
               tabPanel(strong("Financial Ratios Calculator"),icon=icon("chart-bar"),
                        sidebarLayout(
                        sidebarPanel(width=2,h4(strong("Profit figures:")),
                                  actionButton("delete",strong("Clear Fields"),icon=icon("broom")),br(),br(),  
                                  textInput("num","Profit 1",value="100000",width=150),
                                  textInput("numb","Profit 2",value="150000",width=150),
                                  textInput("number","Profit 3",value="200000",width=150),
                                  textInput("numbers","Profit 4",value="250000",width=150),
                                  textInput("numbered","Profit 5",value="300000",width=150),
                                  hr(),
                                  h4(strong("Turnover figures:")),
                                  actionButton("remove",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                                  textInput("fig","Turnover 1",value="350000",width=150),
                                  textInput("figs","Turnover 2",value="300000",width=150),
                                  textInput("figu","Turnover 3",value="420000",width=150),
                                  textInput("figur","Turnover 4",value="600000",width=150),
                                  textInput("figure","Turnover 5",value="550000",width=150),
                                  actionButton("go",strong("Calculate Ratio"),icon=icon("caret-right")),
                                  hr(),
                                  h4(strong("Receivables figures:")),
                                  actionButton("vanish",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                                  textInput("deb","Receivables 1",value="150000",width=150),
                                  textInput("debt","Receivables 2",value="100000",width=150),
                                  textInput("debts","Receivables 3",value="50000",width=150),
                                  textInput("debtor","Receivables 4",value="80000",width=150),
                                  textInput("debtors","Receivables 5",value="170000",width=150),
                                  actionButton("away",strong("Calculate Ratio"),icon=icon("caret-right"))),  
                        mainPanel(h4("The Financial Ratios Calculator makes possible a comparative analysis of a company's profitability and efficiency ratios over time."),hr(),
                                  h3(strong("Profitability Ratios")),h4("(Profit/Turnover): Calculates how much profit margin (%) a company makes on its sales"),column(6,withSpinner(plotOutput("bar",width=400,height=400),type=1)),column(6,withSpinner(plotOutput("pie"),type=1)),
                                  fluidRow(column(6,downloadButton("drop",strong("Download Bar Plot"))),column(6,downloadButton("fall",strong("Download Pie Chart")))),hr(),
                                  h3(strong("Efficiency Ratios")),h4("(Receivables/Turnover): Calculates the average length of time (in days) it takes for a company to recover its debts"),
                                  fluidRow(column(6,withSpinner(plotOutput("sphere"),type=1)),column(6,withSpinner(plotOutput("bin"),type=1))),
                                  fluidRow(column(6,downloadButton("down",strong("Download Pie Chart"))),column(6,downloadButton("plummet",strong("Download Bar Plot")))))
                                  
                                  
                          )),
               tabPanel(strong("Send Us Your Feedback"),icon=icon("envelope"),
                    HTML("<iframe src=https://docs.google.com/forms/d/e/1FAIpQLSex-eKi33LdmZE7L3PwjWm4tFbFoEIw_L_KUvsSi6kgdXgJPA/viewform?embedded=true width=1400 height=1000 frameborder=0 marginheight=0 marginwidth=0>Loading…</iframe>")),
               navbarMenu(strong("More"),
               tabPanel(strong("Graphs and Charts"),icon=icon("chart-bar")),
               tabPanel(strong("Tables"),icon=icon("table")))

)
server<-function(input,output,session){
    
      observeEvent(input$clear,{
      updateTextAreaInput(session,"text",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"texts",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"word",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"words",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"wordy",value="",placeholder="Enter new text")
      
    })
  observeEvent(input$run,{
    shinyalert(title="Running Analysis",text="Please be patient while the app performs the calculations",
               closeOnEsc=TRUE,confirmButtonText="OK",timer=10000,animation=TRUE,closeOnClickOutside=TRUE)
  })
  observeEvent(input$delete,{
    updateTextInput(session,"num",value="",placeholder="0")
    updateTextInput(session,"numb",value="",placeholder="0")
    updateTextInput(session,"number",value="",placeholder="0")
    updateTextInput(session,"numbers",value="",placeholder="0")
    updateTextInput(session,"numbered",value="",placeholder="0")
  })
  observeEvent(input$remove,{
    updateTextInput(session,"fig",value="",placeholder="0")
    updateTextInput(session,"figs",value="",placeholder="0")
    updateTextInput(session,"figu",value="",placeholder="0")
    updateTextInput(session,"figur",value="",placeholder="0")
    updateTextInput(session,"figure",value="",placeholder="0")
  })
  observeEvent(input$vanish,{
    updateTextInput(session,"deb",value="",placeholder="0")
    updateTextInput(session,"debt",value="",placeholder="0")
    updateTextInput(session,"debts",value="",placeholder="0")
    updateTextInput(session,"debtor",value="",placeholder="0")
    updateTextInput(session,"debtors",value="",placeholder="0")
  })
  
  
  doc<-reactive({c(if(nchar(input$text)>0){input$text},
                   if(nchar(input$texts)>0){input$texts},
                   if(nchar(input$word)>0){input$word},
                   if(nchar(input$words)>0){input$words},
                   if(nchar(input$wordy)>0){input$wordy}
             )
    })
  profit<-reactive({
    as.numeric(c(if(nchar(input$num)>0){input$num},
                 if(nchar(input$numb)>0){input$numb},
                 if(nchar(input$number)>0){input$number},
                 if(nchar(input$numbers)>0){input$numbers},
                 if(nchar(input$numbered)>0){input$numbered})
    )
  })
  
  turnover<-reactive({
    as.numeric(c(if(nchar(input$fig)>0){input$fig},
                 if(nchar(input$figs)>0){input$figs},
                 if(nchar(input$figu)>0){input$figu},
                 if(nchar(input$figur)>0){input$figur},
                 if(nchar(input$figure)>0){input$figure})
    )
  })
  
  receivables<-reactive({
    as.numeric(c(if(nchar(input$deb)>0){input$deb},
                 if(nchar(input$debt)>0){input$debt},
                 if(nchar(input$debts)>0){input$debts},
                 if(nchar(input$debtor)>0){input$debtor},
                 if(nchar(input$debtors)>0){input$debtors})
    )
  })
  
  #This is the function for calculating profitability ratio
  profitability<-function(profit,turnover){
   profitability=round((profit/turnover)*100,1)
   return(profitability)
  }
  profitability.ratio<-reactive({profitability(profit(),turnover())})
  
  #This is the function for calculating efficiency ratio
  efficiency<-function(receivables,turnover){
    efficiency<-round((receivables/turnover)*365,1)
    return(efficiency)
  }
  
  efficiency.reactive<-reactive({
    efficiency(receivables(),turnover())
  })
  
  Analyze<-reactive({
    round(analyzeSentiment(
      replace_symbol(
        replace_number(
          replace_ordinal(
            doc())))),1)})
  
  QDAP<-reactive({Analyze()$SentimentQDAP})
  LoughranM<-reactive({Analyze()$SentimentLM})
  HarvardIV<-reactive({Analyze()$SentimentGI})
  
  word.count<-reactive({countWords(doc(),removeStopwords=FALSE)})
  
  tables<-reactive({
    data.frame(QDAP(),LoughranM(),HarvardIV())
  })
  
  data<-reactive({switch(input$choice,
                         "QDAP"=tables()$QDAP,
                         "LoughranM"=tables()$LoughranM,
                         "HarvardIV"=tables()$HarvardIV)})
  
  
  output$download<-downloadHandler(
    filename=function(){
      paste("table",".csv",sep="")
    },
    content=function(file){
      write.csv(tables(),file)
    }
  )
  
  output$drop<-downloadHandler(
    filename=function(){
      paste("Barplot",".jpg",sep="")
    },
    content=function(file){
      jpeg(file)
      barplot(profitability.ratio(),
              col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
              beside=TRUE,
              border="white",
              names.arg=c("Year 1","Year 2","Year 3","Year 4","Year 5"),
              xlab="Years",
              ylab="Margins in (%)")
      dev.off()
    }
  )
  
  output$fall<-downloadHandler(
    filename=function(){
      paste("Piechart",".jpg",sep="")
    },
    
    content=function(file){
      jpeg(file)
      pie(profitability.ratio(),radius=1.1,col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
          border="white",
          clockwise=TRUE,
          init.angle=90,
          labels=profitability.ratio())
      dev.off()
    }
  )
  
  output$down<-downloadHandler(
    filename=function(){
      paste("Piechart",".jpg",sep="")
    },
    
    content=function(file){
      jpeg(file)
      pie(efficiency.reactive(),radius=1.1,border="white",clockwise=TRUE,
          init.angle=90,
          labels=efficiency.reactive(),
          col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"))
      dev.off()
    }
  )
  
  output$plummet<-downloadHandler(
    filename=function(){
      paste("Barplot",".jpg",sep="")
    },
    content=function(file){
      jpeg(file)
      barplot(efficiency.reactive(),names.arg=c("Year 1","Year 2","Year 3","Year 4","Year 5"),
              col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"),
              border="white",
              beside=TRUE,
              xlab="Years",
              ylab="Days")
      dev.off()
    }
  )
  
  output$plot.down<-downloadHandler(
    filename=function(){
      paste("Graph",".jpg",sep="")
    },
    content=function(file){
      jpeg(file)
      color<-switch(input$color,
                    "Blue"="#5dade2",
                    "Red"="#e74c3c",
                    "Green"="#1abc9c",
                    "Yellow"="#f7dc6f",
                    "Purple"="#a569bd")
      barplot(data(),col=color,border="white",xlab="Texts",ylab="Sentiment Scores",main="Bar Plot of Sentiment Scores")
      dev.off()
    }
  )
  
  output$table<-renderReactable({
      input$run
      isolate(reactable(tables(),searchable=TRUE,bordered=TRUE,defaultColDef=colDef(
      align="center",
      headerStyle=list(background="#5dade2"),
      style=function(value){
        if(value>0){color<-"#27ae60"}
        else if(value<0){color<-"#e74c3c"}
        else{color<-"#5dade2"}
        list(color=color,fontWeight="bold")
      }),
      highlight=TRUE,outlined=TRUE,striped=TRUE,filterable=FALSE,compact=TRUE,onClick="expand")
      )
  })
  
  output$count<-renderReactable({
        input$run
        isolate(reactable(data.frame(word.count()),bordered=TRUE,striped=TRUE,compact=TRUE,
                          defaultColDef=colDef(
                            align="center",
                            headerStyle=list(background="#85c1e9"))
                            ))
       })
  
  output$plot<-renderPlot({
        
    color<-switch(input$color,
                  "Blue"="#5dade2",
                  "Red"="#e74c3c",
                  "Green"="#1abc9c",
                  "Yellow"="#f7dc6f",
                  "Purple"="#a569bd")
     input$run 
    isolate(barplot(data(),col=color,border="white",xlab="Texts",ylab="Sentiment Scores",main="Bar Plot of Sentiment Scores"))
    
  })
  output$graph<-renderPlot({
        
            input$run
            isolate(plotSentiment(data(),xlab="Texts",ylab="Sentiment Scores"))
      })
  
  output$bar<-renderPlot({
    
            input$go
            isolate(barplot(profitability.ratio(),
                            col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
                            beside=TRUE,
                            border="white",
                            names.arg=c("Year 1","Year 2","Year 3","Year 4","Year 5"),
                            xlab="Years",
                            ylab="Margins in (%)"))
                            
    
  })
  
  output$pie<-renderPlot({
    
            input$go
            isolate(pie(profitability.ratio(),radius=1.1,col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
                        border="white",
                        clockwise=TRUE,
                        init.angle=90,
                        labels=profitability.ratio()))
            
            
          
  })
  
  output$sphere<-renderPlot({
    
    input$away
    isolate(
      pie(efficiency.reactive(),radius=1.1,border="white",clockwise=TRUE,
          init.angle=90,
          labels=efficiency.reactive(),
          col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"))
    )
  })
  
  output$bin<-renderPlot({
    input$away
    isolate(
      barplot(efficiency.reactive(),names.arg=c("Year 1","Year 2","Year 3","Year 4","Year 5"),
              col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"),
              border="white",
              beside=TRUE,
              xlab="Years",
              ylab="Days")
    )
  })
  
  
    
}
}
 
shinyApp(ui=ui,server=server)

However, when I omit some fields and run the calculation, I get the error message below:


  Warning: Error in barplot.default: incorrect number of names
  182: stop
  181: barplot.default
  167: renderPlot [C:/Users/Idiaye/Documents/Analytic/Analytic.R#325]
  165: func
  125: drawPlot
  111: <reactive:plotObj>
   95: drawReactive
   82: origRenderFunc
   81: output$bar
    1: runApp

I would really appreciate your help please. Thanks

Too messy.

I think, if you omitted data in profit or turnover, their length will not be 5 as you expected.
so data is not 5 term but name has 5 term, this situation will make error.

Try to solve it first.

To expand on what @jhk0530, your example app includes a lot of code that is unrelated to the problem. You are more likely to get helpful responses if you create a minimal reprex. You might want to start by reading https://mastering-shiny.org/action-workflow.html#reprex.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.