Search code examples
rggplot2shinyr-plotlyggplotly

ggplot is plotting all my data into a single line


I am making a dashboard that plots an x and y input. However when both inputs are passed, ggplot plots my data into a singular line. I have also tried using plotly and I get no result altogether. Would someone be able to help with a working ggplot and plotly example.

here is the ggplot code portion plus image result

renderPlot({
   p <- ggplot(Merged_data_frame_hcat, aes_string(x=input$x, y=input$y)) + geom_point()
 
   print(p)
  
})

enter image description here

and the plotly code plus image

renderPlot({
  p <- plot_ly(data= Merged_data_frame_hcat,x= ~input$x, y= ~input$y,type = 'scatter', mode = 'lines' )
 
   print(p)
  
})

enter image description here


Solution

  • to debug your code, you can print the data you are using in the console using cat, for example:

    renderPlot({
       cat('input$x=',input$x,'\n')
       p <- ggplot(Merged_data_frame_hcat, aes_string(x=input$x, y=input$y)) + geom_point()
       print(p)
      
    })
    

    If you look at the RStudio console, you'll see the value you're passing to aes_string.
    From your answers in the comments, you'll most probably see in the console:

    shinyApp(ui = ui, server = server)
    
    Listening on http://127.0.0.1
    input$x = 1
    

    This is due to the way selectInput works :

    choices : List of values to select from. If elements of the list are named, then that name --- rather than the value --- is displayed to the user.

    This means that if

    choices = list('dates'=1)
    

    You see dates in the selectInputand you get 1 in input$x.
    For further help, as pointed out by @MrFlick in the first comment, you'll need to provide a simple reproducible example : discovering & solving a problem mainly through comments isn't efficient.