I'm using addPolylines
to overlay contours of a specific value(s) on a leaflet
generated web map, however, addPolylines
is not plotting all the data that it is supplied with. As per the first image, at least two regions of a value of 125 are evident, but leaflet generated map displays only one region.
The data can be downloaded from here, and reproducible script that generates SpatialLinesDataFrame object for addPolylines
and leaflet
generated map as follows:
rm(list=ls())
library(leaflet)
library(maptools)
# create a vector of lon, lat, and read data
lon1 <- seq(-124.938,length=59,by=1)
lat1 <- seq(25.063,length=29,by=1)
data1 <- matrix(scan(file="AnnualPrcpValues.txt"),ncol=length(lat1),byrow = T)
## spatial pattern of precipitation
## I choose a value *125* correspond to light yellow color to plot contours on leaflet generated map
## at least two regions corresponds to this value, i.e., Pacific northwest & Southwest region]
filled.contour(lon1,lat1,data1,color=terrain.colors)
## The following code calculates contour lines correspond to a value *125*
## and then converts contour lines into a SpatialLinesDataFrame object
CL=contourLines(lon1,lat1,data1,levels=c(125))
c.linesSP <- ContourLines2SLDF(CL)
c.linesSP
has co-ordinates for three lines, but, addPolylines
plots contours only for one region
str(coordinates(c.linesSP))
##List of 1
## $ :List of 3
## ..$ : num [1:17, 1:2] -123 -122 -122 -122 -122 ...
## ..$ : num [1:5, 1:2] -125 -124 -123 -124 -125 ...
## ..$ : num [1:9, 1:2] -86.4 -86.9 -87.9 -88.9 -89.9 ...
## leaflet generated map
map1 <- leaflet() %>% addTiles() %>%
setView(lng = -80, lat = 40, zoom = 2)
map2<- map1 %>% addPolylines(data=c.linesSP,color="red")
## It should have three lines, but only one line is seen in the Pacific Northwest region
map2
## However, contour line in the southwest region is plotted when explicilty co-ordinates, i.e., [[1]] [[3]] are supplied
##
tempdata <- coordinates(c.linesSP)[[1]][[3]]
map2 %>% addPolylines(tempdata[,1],tempdata[,2],
weight=1.25,color="green") %>%
addMarkers(tempdata[,1],tempdata[,2])
It is not clear why addPolylines
is not plotting all the coordinates that it supplied with initially. Greatly appreciate suggestions.
Updating to the latest leaflet version from github via
devtools::install_github("rstudio/leaflet")
should solve your problem. Here's mysessionInfo()
with which your code runs just fine and I see 3 lines: