r - 基于单选按钮输入更新叶绿素图
问题描述
我正在创建一个闪亮的仪表板来可视化 COOVID 19 在澳大利亚各州的传播。
以下是我的数据框(covid_cases),其中包含确诊病例数、死亡数和康复数
region Confirmed Deaths Recovered
<chr> <dbl> <dbl> <dbl>
1 Australian Capital Territory 113 3 110
2 New South Wales 4218 53 3118
3 Northern Territory 33 0 31
4 Queensland 1157 6 1141
5 South Australia 468 4 462
6 Tasmania 230 13 217
7 Victoria 20149 787 18901
8 Western Australia 676 9 651
在我的服务器中,我将 covid_cases 数据框与 shapefile 连接起来,并使用“已确认”案例为状态着色。这工作正常。
server <- function(input, output) {
output$ausmap <- renderLeaflet({
states_data <- read_sf("https://raw.githubusercontent.com/rowanhogan/australian-states/master/states.geojson") %>%
dplyr::left_join(covid_cases, by=c("STATE_NAME" = "region"))
pal <- colorQuantile("Blues", domain = states_data$Confirmed)
leaflet(states_data) %>%
addTiles() %>%
addPolygons(fillColor=~pal(Confirmed),
fillOpacity=0.8,
color="white", weight=1) %>%
fitBounds(110.246193, -50.322817, 155.226126, -9.088012)
})
}
但是,我现在想根据用户输入为状态着色。并在我的 UI 组件中实现了以下 radioGroupButtons。
UI <- dashboradBody(
fluidRow(
radioGroupButtons(
inputId = "casetype",
label = NULL,
choices = c("Confirmed", "Deaths", "Recovered"),
selected = "Confirmed"
),
leafletOutput("ausmap")
)
)
并按如下方式更新了我的服务器
server <- function(input, output) {
output$ausmap <- renderLeaflet({
states_data <- read_sf("https://raw.githubusercontent.com/rowanhogan/australian-states/master/states.geojson") %>%
dplyr::left_join(covid_cases, by=c("STATE_NAME" = "region"))
pal <- colorQuantile("Blues", domain = states_data$Confirmed)
leaflet(states_data) %>%
addTiles() %>%
addPolygons(fillColor=~pal(input$casetype),
fillOpacity=0.8,
color="white", weight=1) %>%
fitBounds(110.246193, -50.322817, 155.226126, -9.088012)
})
}
这给了我一个错误,指出“'x'必须是数字”。
我还想根据输入更改调色板(例如:死亡 - 红色,确认 - 蓝色,恢复 - 绿色)。但我不确定如何更新它。
解决方案
我不确定这是否是最好的方法(不知何故,感觉应该用反应值来完成,但我仍在试图找出闪亮的细节......尤其是反应细节:D)......无论如何。 ..这是一个应该有效的解决方案:)
诀窍是对casetype
and使用辅助变量pal
。你得到的错误(数字输入)是,因为 pal 需要数字数据(死亡,...)来映射颜色而不是类别(casetype)
output$ausmap <- leaflet::renderLeaflet({
url <- paste0("https://raw.githubusercontent.com/rowanhogan/",
"australian-states/master/states.geojson")
selected_col <- switch(input$casetype,
"Confirmed"="Blues",
"Deaths"="Reds",
"Recovered"="Greens")
states_data <- sf::read_sf(url) %>%
dplyr::left_join(covid_cases %>%
dplyr::select(region,selected=input$casetype),
by=c("STATE_NAME" = "region"))
pal <- leaflet::colorQuantile(selected_col, domain = states_data$selected)
leaflet::leaflet(states_data) %>%
leaflet::addTiles() %>%
leaflet::addPolygons(fillColor=~pal(selected),
fillOpacity=0.8,
color="white",
weight=1) %>%
leaflet::fitBounds(110.246193, -50.322817, 155.226126, -9.088012)
})
推荐阅读
- javascript - 使用带有渲染功能的 Vue.js 3 片段
- android - 即使应用程序关闭,如何保持广播接收器注册?
- python - 滚动直到屏幕上出现按钮
- c++ - 构造函数中的 C++ 枚举?
- javascript - 如果位置和长度未知/可变,如何替换字符串?
- javascript - 从 msal 2.0 令牌获取 UPN 和电子邮件地址
- python-3.x - Pandas 将月份名称转换为日期
- java - 具有模块化应用程序困难的 Jpackage 创建安装程序
- vue.js - 在页面中显示食谱
- javascript - addEventListener 是否适用于按标签名称获取元素?