PilotWombat
PilotWombat

Reputation: 23

Displaying only those x values selected by the user

I'm new to R. I have a large dataset that I want the user to be able to select the x values plotted on a graph. To make it easier, I've done the same thing using the mpg dataset:

library(shiny)

ui <- fluidPage(
    selectInput(
        inputId= "manuf",
        label= "Manufacturer",
        choices= mpg$manufacturer,
        multiple= TRUE
    ),
    plotOutput("graph1")
)

server <- function(input, output) {
    output$graph1 <- renderPlot({
        ggplot() +
        geom_point (
            mapping = aes (
                x= input$manuf,
                y= ???
            )
        )
    })
}

shinyApp(ui = ui, server = server)

I can't for the life of me figure out what the correct syntax is for the 'y' input. I have been googling my heart out and can't figure it out, and I'm sure it's relatively simple. I want it to only output the data for whatever you've selected in the drop down.

putting in y= mpg$hwy shows ALL hwy datapoints when one manufacturer is selected and throws an error ("Aesthetics must be either length 1 or the same as the data") with more. I think the errors are self-explanatory, but that doesn't help me figure out the correct code for 'y'. Ideas? Thanks in advance.

Upvotes: 0

Views: 228

Answers (2)

neilfws
neilfws

Reputation: 33782

Let's forget about Shiny for a moment and focus on how you would filter a dataset for plotting with ggplot(). The tidyverse approach is to use dplyr::filter:

library(dplyr)
library(ggplot2)

mpg %>% 
  filter(manufacturer == "audi") %>% 
  ggplot(aes(manufacturer, hwy)) + 
  geom_point()

So your server function would look something like this (untested):

server <- function(input, output) {
  output$graph1 <- renderPlot({
    mpg %>%
      filter(manufacturer == input$manuf) %>%
      ggplot(aes(manufacturer, hwy)) +
      geom_point()
  )}
}

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 145765

The aesthetic mappings for ggplot (like aes(x = ...)) should be column names, but you aren't giving the user a choice of column names, you give the user the choice of manufacturer values---which correspond to rows. If you want the user to select certain rows to plot based on the manufacturer, you should subset/filter the data that you give to ggplot, perhaps like this:

library(shiny)
library(ggplot2)

ui <- fluidPage(
    selectInput(
        inputId  = "manuf",
        label    = "Manufacturer",
        choices  = mpg$manufacturer,
        multiple = TRUE
    ),
    plotOutput("graph1")
)

server <- function(input, output) {
    output$graph1 <- renderPlot({
        ggplot(data = mpg[mpg$manufacturer %in% input$manuf, ]) +
        geom_point (
            mapping = aes (
                x = manufacturer,
                y = hwy
            )
        )
    })
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions