使用 3 个变量制作 R/Shiny/ggplot2 折线图——日期、state_territory 和离散变量

Make R/Shiny/ggplot2 linegraph using 3 variables--date, state_territory, and discrete variable

我的数据框是 tableau_jh_df [显示前 4 行]:

date province_state number_of_cases
1 2020-01-22 Alabama 0
2 2020-01-22 Alaska 0
3 2020-01-22 Arizona 0

根据 Shiny 控件中用户选择的 province_state,我想绘制折线图 每周使用 ggplot2 的总数 number_of_cases。到目前为止我得到的是所有案例 无论选择哪个 province_state。这是我的代码和图表:

# ui
fluidRow(
        column(3,
               selectInput("state_terr", "Choose a State/Territory:",
                           list("Alabama", "Alaska", "Arizona" [,...etc]  
# server
output$plot <- renderPlot({
    min_date <- as.Date("2020-01-20")
    max_date <- NA
    ggplot(tableau_jh_df, aes(date, number_of_cases, col = input$state_terr,
                              group = 1)) +
    geom_line() +
    labs(x = "Date", y = "Number of Cases") +
    theme(axis.text.x = element_text(angle = 45),
          axis.text.y = element_text(angle = 90))  

Number of Cases by Date

您必须根据所选的州或省过滤您的数据集。使用 dplyr 中的 filter 试试这个:

ggplot(filter(tableau_jh_df, province_state == input$state_terr), 
       aes(date, number_of_cases, col = input$state_terr, group = 1)) +
    geom_line() +
    labs(x = "Date", y = "Number of Cases") +
    theme(axis.text.x = element_text(angle = 45),
          axis.text.y = element_text(angle = 90))

顺便说一句:如果那是您的意图,col = input$state_terr 对线条的颜色没有影响。