The leaflet package for online mapping in R(转)
It has been possible for some years to launch a web map from within R. A number of packages for doing this are available, including:
- RgoogleMaps, an interface to the Google Maps api
- leafletR, an early package for creating Leaflet maps with R
- rCharts, which can be used as a basis for webmaps
In this tutorial we use the new RStudio-supported leaflet R package. We use this package, an R interface to theJavaScript mapping library of the same name because:
- leaflet is supported by RStudio, who have a track strong track record of creating amazing R packages
- leaflet appears to provide the simplest, fastest way to host interactive maps online in R, requiring only 2 lines of code for one web map! (as you’ll see below)
- leaflet is shiny. Shiny in the literal sense of the word (a new and fresh approach to web mapping in R) but also in the sense that it works well with the R package shiny.
The best tutorial resource I have found on leaflet is this vignette by Joe Cheng and Yihui Xie. Building on their excellent description, this article explains some of the fundamentals of the package.
Installing leaflet
Because leaflet is new, it’s not yet on CRAN. Even when it does appear, installing from github may be a good idea, to ensure you have access to the latest features and bug fixes. Here’s how:
# Install leaflet package
if(!require(leaflet)) install_github("rstudio/leaflet")
A first web map with leaflet
To create an interactive web map with leaflet is incredibly easy. Having installed the package try this single line of code:
# Plot a default web map (brackets display the result)
(m <- leaflet() %>% addTiles())
img <- readPNG("~/repos/Creating-maps-in-R/figure//shiny_world.png")
grid.raster(img)
Adding basic features with %>%
Adding basic features to your webmap is easy. The %>%
‘pipe’ operator used extensively in dplyr and developed for the maggrittr package means we can finally escape from dozens of nested bracketted commands. (If you use RStudio, I suggest trying the new shortcut Ctl+Shift+M
to produce this wonderful operator.) leaflet settings and functionality can thus be added sequentially, without requiring any additional brackets!
To add a location to the map m
, for example, we can simply pipe m
into the function setView()
:
m %>% setView(lng = -1.5, lat = 53.4, zoom = 10) # set centre and extent of map
This way we can gradually add elements to our map, one-by-one:
(m2 <- m %>%
setView(-1.5, 53.4, 10) %>% # map location
addMarkers(-1.4, 53.5) %>% # add a marker
addPopups(-1.6, 53.3, popup = "Hello Sheffield!") %>% # popup
# add som circles:
addCircles(color = "black", runif(90, -2, -1), runif(90, 53, 54), runif(90, 10, 500)))
Adding data
In the previous example, we added some random data that we created locally, inside the function call. How do we use real, large datasets in leaflet? The package provides 3 options:
- Data from base R: lat/long matrix or data.frame
- Data from sp such as SpatialPoints and SpatialPolygons
- Data from maps
Let’s try adding a bicycle route, one that I followed with some friends to move from Sheffield to my current home of Leeds. First download some data:
url = "https://github.com/Robinlovelace/sdvwR/raw/master/data/gps-trace.gpx"
download.file(url, destfile = "shef2leeds.gpx", method = "wget")
Now we can load this as a SpatialLinesDataFrame
and display in leaflet:
library(rgdal)
shef2leeds <- readOGR("shef2leeds.gpx", layer = "tracks")
m2 %>%
setView(-1.5, 53.4, 9) %>% # map location
addPolylines(data = shef2leeds, color = "red", weight = 4)
Note in the above example that we had to use the argument data =
to refer to our spatial object: it cannot simply be inserted without specifying what it is. The data
argument can also be placed inside the initialleaflet()
function call.
That was quite a painless process that would many more lines of code if you were to use JavaScript. But not as painless as the bicycle trip itself, which involved fewer lines of code still: 0! This can be seen in the following video.
Shiny integration
leaflet is developed by the same team who develop shiny so the two are well integrated. Below is a very simple example, modified slightly from the package’s vignette:
library(shiny)
shinyApp(
ui = fluidPage(leafletOutput('myMap')),
server = function(input, output) { # download and load data
url = "https://github.com/Robinlovelace/sdvwR/raw/master/data/gps-trace.gpx"
download.file(url, destfile = "shef2leeds.gpx", method = "wget", )
library(rgdal)
shef2leeds <- readOGR("shef2leeds.gpx", layer = "tracks") map = leaflet() %>% addTiles() %>% setView(-1.5, 53.4, 9) %>%
addPolylines(data = shef2leeds, color = "red", weight = 4)
output$myMap = renderLeaflet(map)
}
)
Applications
Clearly leaflet
is a powerful and flexible R package. If I were to offer one critique, it would be that I could find no easy way to allow the user to query the data objects loaded. plotly, for example, provides a description of any visual object the user clicks on. The datashine commuter visualisation, for example allows users to click on any point, resulting in a burst of lines emenating from it. This would also be possible in leaflet/shiny, but the best implementation is not immediately clear, to me at least!
The wider context of this article is the pressing need for better transport planning decision making, to enable a transition away from fossil fuels. To this end, the ‘propensity to cycle’ project, funded by the UK’sDepartment for Transport, seeks to create an interactive tool to identify where new bicycle paths are most needed. There are clearly many other uses for R’s leaflet package: what will you use it for? Let me know at@robinlovelace.
转自:http://robinlovelace.net/r/2015/02/01/leaflet-r-package.html
The leaflet package for online mapping in R(转)的更多相关文章
- 解决Package is not available (for R version XXX)?
目录 1. 更新R(不推荐) 2. 更改或指定镜像源 3.源码安装 安装R包时这个错误是经常见到的.我认为有几个方法可解决,记录之. 1. 更新R(不推荐) 简单粗暴的方法就是更新R,但这波及的范围太 ...
- R扩展包
log10() .libPaths()#查看R包目录 library()#查看以前安装的函数 search() #安装R包的方式 install.packages("car")#安 ...
- 轻松创建R语言函数包
讲真,用R这么几年,始终未尝试过写自己的包,看来这就是我与真正程序员的差距了——编程习惯等于没有. 昨天一个偶然的机会想开始写自己的工具包,发现了前期教程的有一些过时.于是,写一个**windows* ...
- R语言 recommenderlab 包
recommend li_volleyball 2016年3月20日 library(recommenderlab) ## Warning: package 'recommenderlab' was ...
- R语言-神经网络包RSNNS
code{white-space: pre;} pre:not([class]) { background-color: white; }if (window.hljs && docu ...
- arcpy.mapping常用四大件-StyleItem
arcpy.mapping常用四大件-StyleItem by 李远祥 StyleItem 笔者将其归类到arcpy.mapping的四大件当中,主要是因为它的独特之处,就是其能力是直接读取.styl ...
- arcpy.mapping实战-专题图制图自动化
arcpy.mapping实战-专题图制图自动化 by 李远祥 最初对arcpy.mapping感兴趣是因为一次大规模的专题地图调整的需要,由于某某单位利用ArcEngine编写的专题图出图系统,出现 ...
- arcpy.mapping常用四大件-MapsurroundElement
arcpy.mapping常用四大件-MapsurroundElement by 李远祥 在arcpy.mapping 中,除了数据入口MapDocument.图层Layer之外,另一重要的角色就是M ...
- arcpy.mapping常用四大件-MapDocument
arcpy.mapping常用四大件-MapDocument by 李远祥 点开arcpy.mapping的帮助,可以看到其有限的几个类,看起来东西不是很多,但却是非常的使用.由于arcpy定位就是粗 ...
随机推荐
- jmeter、java自动化学习地址
自动化学习社区地址:http://www.hordehome.com/c/14-category jmeter学习地址(范丰平博客):http://www.cnblogs.com/fengpingfa ...
- Java 9 尝鲜之JShell交互式编程环境
JShell--Java 9 的交互式编程环境 本文要求读者有基本的 Java 知识. Tips Java 9 的代码由于提供了新特性,所以有些代码并不支持向后兼容.也就是说,用 Java 9 写的代 ...
- Neuron:Neural activities in V1 create a bottom-up saliency map
Neural activities in V1 create a bottom-up saliency map 本文证明了人类的初级视皮层可以在视觉信息加工的非常早期阶段,生成视觉显著图,用以引导空间 ...
- CI Weekly #17 | flow.ci 支持 Java 构建以及 Docker/DevOps 实践分享
这周一,我们迫不及待写下了最新的 changelog -- 项目语言新增「Java」.创建 Java 项目工作流和其它语言项目配置很相似,flow.ci 提供了默认的 Java 项目构建流程模版,快去 ...
- 【PAT_Basic日记】1002. 写出这个数
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { void print ...
- JavaWeb开发之HttpServletResponse
1. HttpServletResponse简介 Web服务器回送给Web客户端的HTTP响应消息分为三个部分:状态行,响应消息头,响应体. Servlet API中定义了ServletRespons ...
- Linux - 进程调度算法
进程调度: 无论是在批处理系统还是分时系统中,用户进程数一般都多于处理机数.这将导致它们互相争夺处理机.另外,系统进程也同样需要使用处理机. 这就要求进程调度程序按一定的策略,动态地把处理机分配给处于 ...
- nginx下的几种包管理器
一般来说著名的linux系统基本上分两大类: 1.RedHat系列:Redhat.Centos.Fedora等 2.Debian系列:Debian.Ubuntu等 RedHat系列: 1 ...
- Linux 系统管理06--磁盘管理
Linux系统管理06——磁盘管理 一.磁盘结构 1.硬盘的物理结构 盘片:硬盘有多个盘片,每个盘片2面 磁头:每面一个磁头 2.硬盘的数据结构 扇区:盘片被分为多个扇形区域,每个扇形区存放512字节 ...
- OpenCV 玩九宫格数独(二):knn 数字识别
欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者:刘潇龙 前言 首先需要说明,这里所说的数字识别不是手写数字识别! 但凡对机器学习有所了解的人,相信看到数 ...