首页 > 解决方案 > 反应图是映射变量名吗?

问题描述

我正在尝试创建一个反应图,您可以在其中选择 selectInput() 中的种族并查看中西部该种族的人口。

这是我的用户界面:

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
  )
)

这是我的服务器:

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
  })
}

当我运行shinyApp 时,我不断得到一个条形图,它显示列名而不是列中的数据。

编辑:我认为这是一个简单的错误,我使用 aes 而不是 aes_string

标签: rggplot2shiny

解决方案


当您aes(x = state, y = input$ethnicity)在 ggplot 调用中写入时,它将state在数据集中midwest_ethnicity查找 x 轴的变量。y 也一样,它会寻找一个名为 White 的变量,例如,如果这是input$ethnicity.

我认为您的数据集中没有具有这样名称的变量。

input$ethnicity如果是这种情况(White 是数据集的变量),如果 ggplot 不将其视为字符串而不是值,它将无法工作。你可以测试一下y = get(input$ethnicity)

评论中提出的另一个选项是使用aes_string()而不是aes().


推荐阅读