当前位置:网站首页>Map R language
Map R language
2022-07-28 17:39:00 【Dermatology Dabai】
leaflet package
LeafletR Mainly used R The grammar of the language encapsulates JS Version of Leaflet, Can be in R Linguistic plot window , utilize html5 Technology displays various maps , You can also draw your own element graphics .
It has the following functions :
Interactive map browsing ( The zoom 、 translation )
Use a variety of underlays for any combination
Load map tiles (WMTS)
Point feature locator
Polygon feature markers
Line feature tags
Pop-up window
Parse load GeoJson
from R perhaps RSutido Create a map window
You can embed the map knitr/R Package generated Markdown In the document , Or is it Shiny To make the APP in .
It can be obtained directly through SP Bao Shengcheng ( load ) Spatial objects and data frames containing longitude and latitude are displayed .
You can set the map range and encapsulate custom mouse events .

Generally speaking , Its basic use steps are as follows :
1、 load leaflet package
2、 adopt leaflet Package create map control .
3、 Through the method of layer operation ( Such as addTiles、 addMarkers、 addPolygons) To process layer data , And modify various parameters of the map plug-in , To display the layer on the map control .
4、 You can repeat step 3 , You can add more layer data .
5、 Display the map components . Complete the drawing .
Here's an example :
m <- leaflet()
at <- addTiles(m)
addMarkers(at,lng=116.391, lat=39.912, popup=" This is Beijing ")
leaflet()%>%addTiles()%>%addMarkers(lng=116.391, lat=39.912, popup=" This is Beijing ")

In the official documents , For this kind of writing that requires repeated container nesting , Pipeline operators are provided “%>%” To achieve , Its main function is to put the previous sentence ( Variable ) Pass to the next statement , And as the first parameter , The three sentences above , Use the pipe operator to write , as follows , The output result is exactly the same , But the sentence becomes simple .
Two 、 Map control
stay leaflet When the package is initialized , The general call leaflet() This method , This method is to initialize the map control , A map container will be generated , All layer operations in the future , All in this container . Generally speaking , This method is used as the first parameter of other methods . We can set parameters by display or by pipeline operators %>% To pass this container to other methods .
The basic methods of map control include the following three :
setView() : Set the display level and zoom scale of the map 、 And the center of the map .
fitBounds(): Set the scope of the map , It is usually a rectangle , Structure is :[lng1, lat1] – [lng2, lat2].
clearBounds(): Clear the range setting of the map .
Here's an example :
m<- leaflet()
m<- setView(m,lng=116.38,lat=39.9,zoom=9)
addTiles(m)
Or use the pipe operator
leaflet()%>%setView(lng=116.38,lat=39.9,zoom=9)%>%addTiles()

Initialization is changed to 3 Class words , give the result as follows :
leaflet()%>%setView(lng=116.38,lat=39.9,zoom=3)%>%addTiles()

leaflet Packages support various objects related to spatial information , Including the use of sp Space object defined by package , and R Data frame with spatial information in language , As shown below :
And R dependent :
The matrix is composed of longitude and latitude information
Data frame with latitude and longitude fields .
And sp Package related :
SpatialPoints[DataFrame]
Line/Lines
SpatialLines[DataFrame]
Polygon/Polygons
SpatialPolygons[DataFrame]
And that is maps Various spatial graphic information in the bag
These objects can be used directly leaflet The method inside , Add to the map as a layer . So let's go through leaflet To draw some maps
Of course , The simplest , Or draw points , Through latitude and longitude , Draw the dots , Our husband orders randomly in a batch :
df = data.frame(Lat = rnorm(100), Lon = rnorm(100))
Then draw it :
m <-leaflet(df)
addCircles(m)
# How to write it 2:
df %>%leaflet()%>%addCircles()
leaflet Compared with other map packages , There are many advantages and disadvantages ,
First , Drawing a map is simple and fast , Because they are all based on suppliers tiles, A line of code can render Basic widget Map .
Support pipeline parameter transfer , Add layer by layer , The code structure is clearer .
secondly , There's a lot of tiles Suppliers can choose , Including Gaud 、google、Stamen, Esri, OpenWeatherMap,NASA,
Wait for dozens tiles supplier . Of course, some of them need to be registered . Among them google You can bypass registration , It's very rare .
For adding markers Icon ,shapes shape , Lines, etc , Extremely convenient , This is in ggplot2 It is difficult to do .
Support grid data ,rasters Raster data is a map based on pixels . It can be seen that ,leaflet It is highly inclusive .
Support multiple projection coordinate systems , You can even customize the coordinate system , This is very important in some special scenes .
Of course, there is more important , It has certain interaction ability , You can zoom and drag ,
Simple layer switching does not need to be used Shiny. Make it easier to get started .
Other features , First tiles It is based on suppliers , It has to be networked ,
Secondly, the color support is different , Only support HEX Sum of color Spaces colors() Color names in . Of course, there are several built-in palette function , Very special .
1.Widget Set up
Widget Map box settings , To be sure Widget The basic parameters of ,
Include CRS Coordinate system ,widget The central coordinates of ,zoom level( The zoom ) The scope of the , widget Boundary coordinates ,data Data etc. .
1.1
leafletOptions()
leaflet() There was a options Parameters , use leafletOptions() Function to specify , Can be controlled widget Zoom range .
grammar :
1leafletOptions(minZoom = NULL, maxZoom = NULL, crs = leafletCRS(),
2 worldCopyJump = NULL, preferCanvas = NULL, …)
The key parameters :
minZoom, Represents the minimum reduction factor , Apply to all map layers .
maxZoom, Represents the maximum magnification , Apply to all map layers .
crs, Indicates the specified coordinate system ,
preferCanvas, To indicate whether or not to leaflet.js The path appears on the map .
1library(leaflet)
2
3leaflet(options= leafletOptions(minZoom=0, maxZoom =18))
1.2
center 、 The zoom 、 The border
The key function :
setView() , Set the map view( Include center Location and zoom level)
flyTo() , Switch to a specified location or zoom-level, Use smooth pan-zoom
fitBounds() , Set the boundary of the rectangular area of the map .view Limit to [lng1, lat1] - [lng2, lat2]
flyToBounds() , Switch to a specified rectangular area boundary of the map , Use smooth pan/zoom
setMaxBounds() , Limit the maximum boundary of the rectangular area of the map
clearBounds() , Clear the border of the rectangular area of the map , then view It will only be limited by the longitude and latitude data of the map layer .
grammar :
setView(map, lng, lat, zoom, options = list())
flyTo(map, lng, lat, zoom, options = list())
fitBounds(map, lng1, lat1, lng2, lat2, options = list())
flyToBounds(map, lng1, lat1, lng2, lat2, options = list())
setMaxBounds(map, lng1, lat1, lng2, lat2)
ClearBounds (map)
Parameter interpretation :
map, Express leaflet() Created map widget
lng, Express map center Longitude of , East longitude is positive
lat, Express map center Latitude of , North latitude is positive
zoom, Express zoom level
options, List reference , Pass on zoom or pan Parameters .
lngl, latl, lng2, lat2, Express widget The coordinates of the boundary .
1library(leaflet)
2
3# Set the center coordinates and zoom level
4m <- leaflet() %>% addTiles() %>% setView(-71.0382679,42.3489054, zoom =18)56
# Show the first view
7m %>% fitBounds(-72,40,-70,43)
# Set up view The border 89# Show the second view
10m %>% clearBounds() # Clear boundary restrictions , leaflet() Default to world map
Data data
there Data It's not just drawing the data of administrative areas on the map , And include the data to be presented on the map .
Most layer adding functions have data Parameters , Usually use %>% Pipe symbols are gradually passed data Parameters .
leaflet() The following forms of data are usually supported .
Matrix data ( It consists of longitude and latitude ).
Data frame ( It consists of longitude and latitude ).
from sp Data transmitted by the package , Include :
SpatialPoints( Data frame type )
Line()/Lines()
SpatialLines()( Data frame type )
Polygon()/Polygons()
SpatialPolygons()( Data frame type )
from maps Data transmitted by the package , Mainly map() Data frame passed by function .
For longitude and latitude, form matrix or data frame type data , On the move data When adding layers , Guess and match according to the variable name :
If the variable name is lat, or latitude etc. , Then guess the latitude , When guessing , Case insensitive .
If the variable name is lng, long or longitude etc. , Then guess longitude , When guessing , Case insensitive .
You can also manually specify longitude and latitude variables , Use ~ grammar .
During parameter passing , Default the following data Parameters override the previous data Parameters .
1.3.1 data Designation of mid latitude and longitude / guess / Cover
1library(leaflet)23# Auto guess match
4set.seed(123)5df <- data.frame(Lat = 1:10, Long = rnorm(10))6leaflet(df)%>%addCircles()78# Manually specify longitude and latitude variables , Results the same leaflet(df) %>% addCircles(lng = ~Long,
9# lat = ~Lat)
1011# stay add_xxx() Re specify parameters in the function to override , Results the same leaflet() %>%
12# addCircles(data = df) leaflet() %>% addCircles(data = df, lat = ~Lat, lng
13# = ~Long)
1.3.2 sp Object's data
1library(leaflet)
2library(sp)
3library(RColorBrewer)
4
5Sr1 <- Polygon(cbind(c(2,4,4,1,2), c(2,3,5,4,2)))
#4 For non repeating point coordinates , end to end
6Sr2 <- Polygon(cbind(c(5,4,2,5), c(2,3,2,2)))
#3 For non repeating point coordinates , Draw a triangle
7Sr3 <- Polygon(cbind(c(4,4,5,10,4), c(5,3,2,5,5)))
#4 For non repeating point coordinates , Draw a quadrilateral
8Sr4 <- Polygon(cbind(c(5,6,6,5,5), c(4,4,3,3,4)), hole = TRUE) # hole = TRUE, It means hollow
9
10
11Srs1 <- Polygons(list(Sr1),"s1") #'s1' Appoint ID Parameters , Only multiple polygons ID Parameters ,Polygon() No, ID Parameters
12Srs2 <- Polygons(list(Sr2),"s2")
13Srs3 <- Polygons(list(Sr4, Sr3),"s3/4") # Merge Sr3 and Sr4 polygon
14
15# List reference , Pass multiple polygon parameters
16SpP <- SpatialPolygons(list(Srs1, Srs2, Srs3),1:3)
17
18leaflet(height ="300px") %>% addPolygons(data = SpP, fillColor = brewer.pal(3,19name ="Set1"))
1.3.3 from maps In the package for data
1library(leaflet)
2library(maps)
3library(RColorBrewer)
4
5mapStates <- map("state", fill = TRUE, plot = FALSE)
6leaflet(data= mapStates) %>% addTiles() %>% addPolygons(fillColor = brewer.pal(10,7 name="Paired"), stroke = FALSE)
1.3.4 Other parameters
Other drawing parameters support R The type of data that comes with it , Such as : vector , Color vector , Data frame , It also supports ~ Appoint .
1library(leaflet)
2
3# Make up a random data
4m <- leaflet() %>% addTiles()
5df <- data.frame(lat = rnorm(100), lng = rnorm(100),size= runif(100,5,20),
6color= sample(colors(),100))
7
8m <- leaflet(df) %>% addTiles()
9#circle The radius of the icon does not change zoom change :
10m %>% addCircleMarkers(radius = ~size,color= ~color, fill = FALSE)
11#circle The radius of the icon does not change zoom change :
12m %>% addCircleMarkers(radius = runif(100,4,10),color= c("red"))
2.Basemaps Base map
leaflet Support Tilemap Base map of type ,
leaflet Support a variety of free third parties providers Of tiles, Include Stamen, Esri, OpenWeatherMap etc. ,
use names(providers) You can see all of providers.
2.1
Default Tiles(OpenStreetMap)
Use addTiles() Function add tiles And use the default parameters , The default is OpenStreetMap, Block Tiles.
1library(leaflet)
2
3m <- leaflet()%>%setView(lng = -71.0589, lat = 42.3601, zoom = 12)4m%>%addTiles()# Show the street map
The third party Tiles
call addProviderTiles() function , In the parameter providers$ Back plus tiles Just the name of the supplier . We need to pay attention to : Some third parties tiles Need to register .
adopt options Parameter call providerTileOptions() Function can avoid some tiles Registration of .
If there is customized tiles Template URL link , Can be in addTiles() Call in function .
1library(leaflet)
2
3m <- leaflet()%>%setView(lng = -71.0589, lat = 42.3601, zoom = 12)
4
5# Use Stamen.Toner Of tiles
6m%>%addProviderTiles(providers$Stamen.Toner)
Clever data conversion
By calling functions addWMSTiles() You can add WMS(Web Map Service) Of tiles.
Web Map service (WMS) It's a standard protocol , Describe how to pass through Internet Provide any geographical registration map image ,
This is usually generated by a map server using data from a GIS database .
The protocol standard consists of Open Geospatial Consortium(OGC) Development ,
And in 1999 First released in 2004 .WMS Provides a way to use HTTP A simple method of requesting geographical registration map image by interface .
WMS supplier (https://en.wikipedia.org/wiki/Web_Map_Service)
1library(leaflet)
2
3leaflet() %>% addTiles() %>% setView(-93.65,42.0285, zoom =4) %>% # Stack one WMS Of tiles Layers 4addWMSTiles("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", layers ="nexrad-n0r-900913",
5 options = WMSTileOptions(format ="image/png", transparent = TRUE), attribution ="Weather data <U+00A9> 2012 IEM Nexrad")
Tiles Layer overlay
Multiple Tiles Layers can also be superimposed , But this situation is usually only used for the surface tiles Is translucent ,
Or in the options Manually specify the opacity in the parameter opacity.
opacity from 0( Completely transparent ) To 1( Completely opaque ).
1library(leaflet)
2
3m <- leaflet() %>% setView(lng = -71.0589, lat =42.3601, zoom =12)
4
5m %>% addProviderTiles(providers$MtbMap) %>% # Bottom tiles
6 addProviderTiles(providers$Stamen.TonerLines, # Stack one layer tiles, Show roads and streets
7 options = providerTileOptions(opacity =0.35)) %>% # opacity Set opacity
8 addProviderTiles(providers$Stamen.TonerLabels) # superposition tiles, Display the road name , Street name , Airport icon .
link :https://blog.csdn.net/R3eE9y2OeFcU40/article/details/88324895
边栏推荐
- 地图R语言
- 产品研发中第三方技术服务的管理
- [Presto] common commands of Presto
- 软件测试培训两个月靠谱吗?
- 小白必看的软件测试发展路线
- Ant financial mobile testing tool solopi monitoring part of the source code guide.. Continuous update
- Uparse rich text style of uni app
- 软件测试真有网上说的那么好吗?
- Batch download files
- Management of third-party technical services in product development
猜你喜欢

Insert text watermark in PDF

Ggplot2 map

Connection design and test platform -- Summary of SystemVerilog interface knowledge points

Shell编程之Sed

数据库优化——深入理解Mysql索引底层数据结构与算法

MySQL detailed learning tutorial (recommended Collection)

【 R语言—基础绘图】

地图R语言

Verilog daily question (vl4 shift operation and multiplication)

Esp-mqtt-at instruction connects Alibaba cloud Internet of things platform
随机推荐
Mysql database development specification
蚂蚁金服移动测试工具solopi监控部分源码导读。。持续更新
JS synchronizes the local time with the server time
AMQP protocol details
Master JVM interview topics and answers offer get soft (with learning roadmap)
软件测试就业前景如何?
Some things encountered in ionic
C#基础面试题(附答案)
No interactive operation of shell script
Export word according to the template, generate compound format tables and variable column tables
掌握JVM面试专题和答案Offer拿到手软(附学习路线图)
软件测试需求人才越来越多,走上测试道路的人却越来越少?
培训软件测试能不能就业
面试官:算法刷题实录.pdf我居然答不上来
特殊质数js实现
在airtest中使用ocr反向识别文本内容
渗透测试大杀器kali安装配置
关于标准IO缓冲区的问题
Using OCR to reverse recognize text content in airtest
技术面轻松通过,HR:只有三年大厂经验的不值20K