[英][R Shiny]: How to filter by time range on the x-axis and simultaneously have two different variables on the y axis in R Shiny app
我想使用 Covid-19 數據( https://data.europa.eu/euodp/de/data/dataset/covid-19-coronavirus-data )構建一個 shiny 應用程序,我想用 ggplot 在哪里顯示條形圖可以看到隨着時間的推移世界范圍內病例或死亡的發展。 我還希望有一個 dateRangeInput ,您可以在其中設置時間段。 同時,我在 y 軸上可以從 selectInput 中選擇變量“cases”或“deaths”。 我可以單獨執行此操作,但我無法弄清楚如何在最后一個 plot 中使用它。 如果我使用以下代碼,它適用於時間范圍:
ui <- fluidPage(
titlePanel("Covid-19 by Country"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "y", label = "Y-Axe:",
choices=c("cases", "deaths"),
selected = "cases"),
dateRangeInput("datum", "Zeitraum auswählen", start = min(covid_worldwide$dateRep), end = max(covid_worldwide$dateRep), min = min(covid_worldwide$dateRep), max = max(covid_worldwide$dateRep), format = "dd.mm.yyyy", language = "de")
),
mainPanel(
plotOutput("covidPlot")
)
)
)
server <- function(input, output, session) {
s <- reactive({
covid_worldwide %>%
filter(
as.Date(dateRep) >= as.Date(input$datum[1]),
as.Date(dateRep) <= as.Date(input$datum[2])
)
})
output$covidPlot <- renderPlot({
ggplot(data= s(), aes(x = dateRep, y = cases)) +
geom_bar(stat="identity", fill="red") + theme_classic() + xlab("Zeitraum") + ylab("Anzahl")
}
)}
shinyApp(ui = ui, server = server)
如果我不更改時間段但為 y 軸提供兩個不同的變量,它也可以工作,請參見以下代碼(UI 與上面相同):
server <- function(input, output, session) {
s <- reactive({
covid_worldwide %>%
filter(
as.Date(dateRep) >= as.Date(input$datum[1]),
as.Date(dateRep) <= as.Date(input$datum[2])
)
})
yvar <- reactive({
if ( "cases" %in% input$y) return(covid_worldwide$cases)
if ( "deaths" %in% input$y) return(covid_worldwide$deaths)
})
output$covidPlot <- renderPlot({
ggplot(data= s(), aes(x = dateRep, y = yvar())) +
geom_bar(stat="identity", fill="red") + theme_classic() + xlab("Zeitraum") + ylab("Anzahl")
}
)}
shinyApp(ui = ui, server = server)
但是,如果我然后嘗試更改 shiny 應用程序中的時間段,我會收到此錯誤:“美學必須是長度 1 或與數據相同 (26852):y” 有沒有人知道如何制作這兩件事在一個 ggplot barplot 工作中? 先感謝您!
您只需在繪圖代碼中的y
上輸入 map input$y
。 此外,由於輸入是一個字符,因此切換到aes_string
而不是aes
很方便,因為它允許將變量作為名稱或字符串傳遞給ggplot()
。
第一個版本不起作用,因為您在y
上使用 map cases
。 第二個不起作用,因為您的反應性yvar
從原始未過濾的 df 中提取向量。 因此yvar
的長度大於過濾后的 df 的行數或日期變量的長度。
output$covidPlot <- renderPlot({
ggplot(data= s(), aes_string(x = "dateRep", y = input$y)) +
geom_bar(stat="identity", fill="red") + theme_classic() + xlab("Zeitraum") + ylab("Anzahl")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.