一种可能的方法是
pivot_longer
数据并在library(shiny)
library(tidyverse)
load(url("https://github.com/bandcar/Unemployment-Rate-Pre-and-Post-Covid/blob/main/ue_wider.RData?raw=true"))
# pivot data to long format
q_long <- q %>%
pivot_longer(cols = -Year, names_to = "State", values_to = "unemployment")
ui <- fluidPage(
titlePanel("US Unemployment Rates Before and After COVID"),
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "y",
label = "State",
choices = unique(q_long$State),
selected = "Alabama",
multiple = TRUE
),
Multiple = TRUE,
selectInput(
inputId = "x",
label = "X-axis:",
choices = c("Year"),
selected = "Year"
),
selectInput(
inputId = "col_p",
label = "Select a Point Color",
choices = c("red", "dark green", "blue", "black"),
selected = "black"
),
selectInput(
inputId = "col_l",
label = "Select a Line Color:",
choices = c("Red", "Blue", "Black", "Dark Green"),
selected = "blue"
),
actionButton("run_plot", "Render Plot")
),
mainPanel(
plotOutput(outputId = "graph")
)
)
)
server <- function(input, output) {
q_filtered <- eventReactive(input$run_plot, {
filter(q_long, State %in% input$y)
})
output$graph <- renderPlot({
ggplot(q_filtered(), aes(x = .data[[input$x]], y = unemployment, color = State)) +
geom_point(color = input$col_p) +
geom_line() +
ylim(2, 15)
})
}
shinyApp(ui = ui, server = server)