R 绘制交互式地图 Mapview
leaflet可以实现交互式地图,这里直接一中国为例,展示不同省份的population以及mapview上的实现。
leaflet基础篇可以去官网;
该文章内容的地图图层文件,均是sf形式。leaflet可以直接加载sf,省去转换Polygons的麻烦。
1.leaflet
1.1 加载China地图
library(ggplot2)
library(dplyr)
library(tibble)
library(sf)
library(leaflet)
library(leaflet.extras)
rm(list = ls())
China=read_sf("https://geo.datav.aliyun.com/areas_v2/bound/100000_full.json")
Anhui=read_sf("https://geo.datav.aliyun.com/areas_v2/bound/340000_full.json")
franconia
breweries
CHNmap=leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons( data=China, stroke = TRUE,
color = "#444444",
weight = 1,
smoothFactor = 0.5,
opacity = 1.0,
fillOpacity = 0.1,
label = ~ name,
highlightOptions = highlightOptions(color = "white",
weight = 2,
bringToFront = TRUE),
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto"))
CHNmap
这里直接加载到leaflet图层上,可以看到China的轮廓及各个省份的位置
1.2 添加安徽地图
在上述的图层中,再添加安徽内部的市及区的地图。
CHNmap %>%
addPolygons( data=Anhui, stroke = T,
color = "blue",
weight = 1,
opacity = 1,
fillOpacity = 0.1)
1.3.根据各个省含有的市及区多少,添加颜色
有时候,需要根据不同省份的人口或者经济,进行不同颜色渲染,突出地区间的比较。现在以各个省份内部所包含的市及县数量,来进行一个等级划分。其中重点是将连续性变量转成分类变量,还要匹配上对应颜。
# set categories and color bins bins = c(0, 5, 10, 15, 20, 30, Inf) pal = colorBin("Reds", domain = China$childrenNum, bins = bins)
## set categories and color bins
bins = c(0, 5, 10, 15, 20, 30, Inf)
pal = colorBin("Reds", domain = China$childrenNum, bins = bins)
## leaflet
map=leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons( data=China, stroke = TRUE,
fillColor = ~pal(childrenNum),
color = "black",
weight = 1,
smoothFactor = 0.5,
opacity = 0.5,
fillOpacity = 0.5,
label = ~ name,
highlightOptions = highlightOptions(color = "green",
weight = 2,
bringToFront = TRUE),
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(data=China, pal = pal,
values = ~childrenNum,
opacity = 0.7,
title = "Number",
position = "bottomright")
# plot
map
1.4.添加点的信息
China_point = st_centroid(China) %>%
st_coordinates() %>%
as_data_frame() %>%
slice(-35)
map %>%
addCircles(data = China_point,
lng = ~X, lat = ~Y,
fillOpacity =2)
2.Mapview 绘图
其实谈到交互地图,mapview包已经做到了精简,详细教程见官网,
这里只需要一行code即可;
但是缺点是,不容易个性化设置,譬如legend名称,legend设置等。
主要是简单,快速。
但是官方文档,里面有更详细的操作步骤。
##
mapview::mapview(China)
mapview::mapview(China,zcol = "childrenNum")
mapview(China, col.regions = "white", lwd = 0.5,legend = F)
后续还会更新,包括怎样将leaflet与mapview结合到shiny中。
及legend细化。
参考
- Drawing interactive maps with Leaflet
- Buffer areas for nearest neighbours or national marine areas delineation
- Interactive Choropleths with Shiny and Leaflet
- Lesson 2 Interactive Maps