1

I'm trying to create an reactive plot where you can select an ethnicity in a selectInput() and see the population of that ethnicity in the midwest.

This is my ui:

ethnicity_sidebar_content <- sidebarPanel(
  selectInput(
    inputId = "ethnicity",
    label = "Select Ethnicity",
    choices = list(
      "Total" = "total",
      "White" = "white",
      "Black" = "black",
      "American Indian" = "amerindian",
      "Asian" = "asian",
      "Other" = "other"
    )
  )
)
ethnicity_main_content <- mainPanel(
  plotOutput("ethnicity_plot")
)
ethnicity_panel <- tabPanel(
  "Midwest by Ethnicity",
  sidebarLayout(
    ethnicity_sidebar_content,
    ethnicity_main_content
  )
)

This is my server:

midwest_poverty <- midwest %>%
  mutate(popbelowpoverty = floor(percbelowpoverty / 100 * poppovertyknown)) %>%
  group_by(state) %>%
  summarise(
    poppovertyknown = sum(poppovertyknown),
    popbelowpoverty = sum(popbelowpoverty)
  ) %>%
  mutate(popabovepoverty = poppovertyknown - popbelowpoverty)

server <- function(input, output) {
  output$ethnicity_plot <- renderPlot({
    p <- ggplot(data = midwest_ethnicity) +
      geom_bar(
        mapping = aes(x = state, y = input$ethnicity),
        stat = "identity"
      )
    p
  })
}

When I run shinyApp, I keep getting a bar plot that graphs the column name rather than the data in the column.

Edit: I think this was a simple mistake where I was using aes instead of aes_string

Supriya
  • 11
  • 3

1 Answers1

0

When you write aes(x = state, y = input$ethnicity) in the ggplot call, it will look for variable state in the dataset midwest_ethnicity for x-axis. Same for y, it will look for a variable named White for instance if this is the value in input$ethnicity.

I don't think there is a variable with such a name in your dataset.

If it is the case (White is a variable of your dataset), it could not work if ggplot don't consider input$ethnicity as a string, and not as a value. You can test y = get(input$ethnicity).

Another option as proposed in comments, is to use aes_string() instead of aes().

demarsylvain
  • 2,103
  • 2
  • 14
  • 33