0

I'm quite new to R and am currently trying to create a simple web app with shiny that plots the longley dataset from R. I want the user to be able to select which trend they want to plot, hence the selctinput in the ui, but I'm currently running into the problem "x and y lengths differ" screenshot of the problem: https://i.stack.imgur.com/zGOtb.png

Below is my reprex

library(shiny)
#> Warning: package 'shiny' was built under R version 4.1.3
mydata <- as.data.frame(longley)

ui<- fluidPage(titlePanel("Economic Data"),
           sidebarLayout(
             sidebarPanel(
               selectInput("Trends", label = ("Trend Index"), 
                           
list("GNP.deflator","GNP","Unemployed","Armed.Forces","Population","Year","Employed"), 
                           selected = "GNP", multiple = TRUE),
             ),
             mainPanel(
               plotOutput(outputId = "lineplot", height = "300px")
             )
           ))


server <- function(input, output) { 
  output$lineplot <- renderPlot({
    color = "434343"
    par(mar= c(4, 4, 1, 1))
    plot(x = mydata$year, y = "Trends", type = "l", xlab = "Date", ylab = "Trend Index", 
col = color, fg = color, col.lab = color, col.axis = color) 
  })
}

shinyApp(ui = ui, server = server)`

Thanks in advance for any help [1]: https://i.stack.imgur.com/zGOtb.png

jjackaryy
  • 1
  • 1
  • There is no `year` column in your data, i.e. `mydata$year` is NULL. The years are the rownames. Also `y = "Trends"` will not pick the column you selected. Use e.g. `y = mydata[[input$Trends]]` which works for one selected column. – stefan Oct 19 '22 at 06:30
  • Thank you so much that's made some progress. If I wanted to plot multiple selected columns at once instead of just the one, how would I go about doing that? – jjackaryy Oct 19 '22 at 07:25
  • I'm not really used to base R plotting. From https://stackoverflow.com/questions/14860078/plot-multiple-lines-data-series-each-with-unique-color-in-r helps I would guess that we need a `for` loop to add a line for each additional column. Personally I would approach this using ggplot2 which however requires a small bit of data wrangling, i.e. reshaping the data to long and filtering for the selected columns. – stefan Oct 19 '22 at 07:31

0 Answers0