我有shapefile,我正在使用readOGR将其读入R,将其转换为SpatialPolygonDataframe。属性表如下图所示。
每行是一个区域(邮政编码区域),并且每天的每个小时都有值,例如:为每个区域测量的h_0,h_1,... h_23。在我的闪亮应用程序中,我想显示一个地图,该地图会随着用户使用sliderInput小部件选择特定时间而发生变化。闪亮的应用程序如下所示:
产生以上结果的代码在这里:
library(shiny)
library(leaflet)
library(reshape2)
library(maps)
library(mapproj)
library(rgdal)
library(RColorBrewer)
library(sp)
library(rgeos)
ui <- fluidPage(
titlePanel("Title"),
sidebarLayout(
sidebarPanel(
tabsetPanel(id= "tabs",
tabPanel("Map", id = "Map",
br(),
p("Choose options below to interact with the Map"),
sliderInput("hour", "Select the hours", min = 0 , max = 23,
value = 7, step = 1, dragRange= TRUE)
)
)
),
mainPanel(
tabsetPanel(type= "tabs",
tabPanel("Map", leafletOutput(outputId = "map"))
)
)
)
)
server <- function(input, output) {
layer <- reactive( {
shp = readOGR("shp",layer = "attractiveness_day3")
shp_p <- spTransform(shp, CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
})
output$map <- renderLeaflet({
bins<- c(0, 2000, 4000, 8000, 16000, Inf)
pal <- colorBin("YlOrRd", domain = layer()$h_7, bins = bins)
leaflet(layer()) %>%
setView(13.4, 52.5, 9) %>%
addTiles()%>%
addPolygons(
fillColor = ~pal(h_7),
weight = 0.0,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7
) %>%
addLegend(pal = pal, values = ~h_7, opacity = 0.7, title = NULL, position = "bottomright")
})
#until here it works but onwards not.
observe(leafletProxy("map", layer())%>%
clearShapes()%>%
addPolygons(
fillColor = ~pal(h_7), # is it possible here to pass column name dynamically
weight = 0.0,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7
) %>%
addLegend(pal = pal, values = ~h_7, opacity = 0.7, title = NULL, position = "bottomright")
)
}
shinyApp(ui, server)
因此,目前在Choropleth映射中填充了静态选择的列h_7
的值。但是我不知道如何以及是否可以基于sliderInput选择动态地传递列名(例如,如果sliderInput值为8,则对应的列为h_8)。然后根据从反应性函数传递到observe
和leafletProxy
函数的选定列来渲染地图。
样本数据:sample data
答案 0 :(得分:1)
可以将列名作为字符串传递。在leafletProxy
中,您可以使用dataset[[column_name]]
链接到列值。使用单个方括号,您不仅可以选择值,还可以选择相应的多边形。
要使您的应用正常运行,您需要在layer()
函数外部调用leafletProxy
。此外,使用clearControls()
删除重复的图例。
最后,我不确定为什么将shapefile放在reactive
表达式中。如果只是将其作为变量添加到server
中,它也将起作用。
observeEvent({input$hour},{
hour_column <- paste0('h_',input$hour)
data = layer()[hour_column]
pal <- colorBin("YlOrRd", domain = as.numeric(data[[hour_column]]), bins = bins)
leafletProxy("map", data=data)%>%
clearShapes()%>%
addPolygons(
fillColor = pal(as.numeric(data[[hour_column]])),
weight = 0.0,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7
) %>% clearControls() %>%
addLegend(pal = pal, values =as.numeric(data[[hour_column]]), opacity = 0.7, title = NULL, position = "bottomright")
})