I can't get crosstalk to work with leaflet and Polylines - here is an MWE:
library(crosstalk)
library(leaflet)
theta <- seq(0, 2*pi, len = 100)
dat <- data.frame(
lon = cos(theta),
lat = sin(theta),
t = 1:100
)
sd <- SharedData$new(dat)
map <- leaflet() %>%
addTiles() %>%
addCircleMarkers(data = sd, lat = ~lat, lng = ~lon, color = "blue") %>%
addPolylines(data = sd, lat = ~lat, lng = ~lon, color = "blue")
bscols(
filter_slider("t", "Time", sd, column = ~t),
map
)
The time filter_slider applies to the circle markers but not the polylines.
Happy to having a go at fixing this in the R leaflet package if someone can point me in the right direction. I.e. what would be required to change / implement? I assume the support is missing on the javascript side as of now?
UPDATE: Good News!
#dmurdoch has submitted a pull request to add support for polylines and polygons.
Using his version of crosstalk, you can now filter leaflet lines/polygons if they're sp objects (note, it doesn't seem to work with sf yet).
First you will need to install this version of crosstalk:
devtools::install_github("dmurdoch/leaflet#crosstalk4")
Then you will need to make sure your features are Spatial objects, easy using rgdal or raster:
shapes_to_filter <- raster::shapefile("data/features.shp") # raster import to 'Spatial Object'
shapes_to_filter <- rgdal::readOGR("data/features.shp") # rgdal import to 'Spatial Object'
Or, if you use sf and dplyr for most spatial tasks (like me) convert an sf object to Spatial:
library(dplyr)
library(sf)
shapes_to_filter <- st_read("data/features.shp") %>% as('Spatial') # sf import to 'Spatial Object'
Then create an sd object for leaflet, and a data frame copy for the filters (IMPORTANT: note how the group for sd_df is set using the group names from the sd_map) :
library(crosstalk)
sd_map <- SharedData$new(shapes_to_filter)
sd_df <- SharedData$new(as.data.frame(shapes_to_filter#data), group = sd_map $groupName())
Create crosstalk filters using sd_df:
filter_select("filterid", "Select Filter Label", sd_df, ~SomeColumn)
Create the map using the sd_map object:
library(leaflet)
leaflet() %>%
addProviderTiles("OpenStreetMap") %>%
addPolygons(data = sd_map)
And any linked tables/charts need to also use the sd_df object:
library(DT)
datatable(sd_df)
Here's all of the sources for the solution:
GitHub Issue
Github pull request from dmurdoch to add support for polygons/lines
Original solution - with outdated method "sd$transform"
Updated example - with the new "group" method, but I couldnt get their RMD to work
As previously mentioned by Bhaskar Karambelkar:
"crosstalk for now works only with markers and not polylines/polygons"
I hope this changes soon.
Related
I want to generate a map of various locations. I want to generate it in R using leaflet package. I have latitude and longtitude of each locations. I have used following code but not able to generate. I am attaching a picture. I want this kind of graph.
library(leaflet)
library(dplyr)
library(tidyr)
jin_map=leaflet() %>%
addProviderTiles("Esri") %>%
addMarkers(lng = jinesh_location_1_$Longitude, lat = jinesh_location_1_$Latitude)
jin_map_circle<-jin_map%>%
clearMarkers()%>%
addCircleMarkers(data=jinesh_location_1_,radius = 2,color = "red",opacity = 0.70)
I've been trying to make a choropleth map with hcmap from highcharter package; I obtained the polygons from my own shapefile because it's a map that is not on the list of highmap's collection.
To do so, first I managed to transform my shapefile to a GeoJson file, as described here:
https://blog.exploratory.io/creating-geojson-out-of-shapefile-in-r-40bc0005857d
Later I managed to draw the map using the package geosonio as described here:
http://jkunst.com/highcharter/highmaps.html#geojsonio-package
However, I can't figure out how to merge a dataframe with values into the polygons drawn in my map. All the examples availables are merging to mapdata that is in a data.frame format, which I lose when transforming to GeoJson.
Here's my code so far:
library(rgdal)
library(geojsonio)
library(highcharter)
#Get map from shapefile
Mymap <- readOGR(dsn="Mymap", "Mymap", verbose = FALSE) %>%
spTransform(CRS("+proj=longlat +ellps=GRS80 +datum=WGS84"))
#Transform to geoJson
MymapJSON <- geojson_json(Mymap)
#Use geojsonio to make data compatible with hcmap
Myhcmap <- jsonlite::fromJSON(MymapJSON, simplifyVector = FALSE)
Myhcmap<- geojsonio::as.json(Myhcmap)
#Draw map:
highchart(type = "map") %>%
hc_add_series(mapData = Myhcmap, showInLegend = T)
Result:
¿How can I put additional data into the GeoJson so I can draw a choropleth?
I finally got to a solution by myself some time ago, it's was fairly simple but since it's not well documented how to add data to the GeoJSON, I will show it here:
#Work with the map until this step:
Myhcmap <- jsonlite::fromJSON(MymapJSON, simplifyVector = FALSE)
#This part was unnecessary:
#Myhcmap<- geojsonio::as.json(Myhcmap)
#Then, write your map like this:
highchart() %>%
hc_add_series_map(Myhcmap, df, value = "value", joinBy = "ID")
Where:
dfis the dataframe you want to append
value is the column name of the data you want to color your map by
joinBy is the joining key variable
The code below is reproducible - it builds the map of the world using leaflet.
I am really not interested in Antarctica and I am more interested in Scandinavia :)
Any way to cut Antarctica or at least force it to be always at the bottom of the map - so that the center of the map is farther north?
Thanks a lot for any pointers!
library(leaflet)
library(rnaturalearth)
countries <- rnaturalearth::countries110
goodnames <- countries$name
goodnames[goodnames %in% goodnames[32]] <- "Ivory Coast"
countries$name[32] <- goodnames[32]
mymap <- leaflet(countries, options = leafletOptions(minZoom = 2))
myvalues <- 1:177
mycolors <- colorNumeric(palette = c("#fee6ce","#e6550d"),
domain = myvalues)(myvalues)
mymap %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
color = ~mycolors,
label = countries$name)
You can use setView to set the initial viewing point to any location of your choosing. If you want this map to focus on Scandinavia on opening, you can do...
mymap <- leaflet(countries, options = leafletOptions(minZoom = 2)) %>% setView(lng=18.6435,lat=60.1282,zoom=2)
The coordinates are simply from searching 'Sweden coordinates' on Google. You can use a site such as https://www.latlong.net/ to help you pick an appropriate center point.
Unfortunately 'rnaturalearth' is not (yet) available fpr R 3.4.2 and I have just updated one second ago so I can't prove my answer. But as you're asking for any pointer -
I use the 'rworldmap' package and take out Antarctica by excluding it after the map is defined by the package.
According to this my suggestion to your code would be:
mymap <- mymap[-which(row.names(mymap)=='Antarctica'),]
Is it possible to style a TopoJSON file from its features for a choropleth using R/leaflet? Tried a few things, and I'm not sure if this is impossible with the leaflet package or if I just don't have the syntax right, especially accessing the properties to enter in the pal() function. Here's what I have:
pal<-colorNumeric(palette ="YlOrRd",domain = USAdata$GINI) #USAdata data frame I merged with the spdf before converting it to shp/topojson
map<-leaflet() %>%
addTiles(options=tileOptions(minZoom = 3)) %>%
setMaxBounds(-167.276413,5.499550,-52.233040, 83.162102) %>%
setView(93.85,37.45,zoom =3) %>%
#addGeoJSON(geojson = jso5)
addTopoJSON(topojson=jso, fillColor = ~pal("GINI"))
#addPolygons(data=poly)
this throws up an error:
"Error in UseMethod("doResolveFormula") :
no applicable method for 'doResolveFormula' applied to an object of class "NULL""
I also tried converting it to an R object the topojson with fromJSON() and adding style elements, but this won't load after I try send it back with toJSON().
Not sure if relevant, but the topojson was created from a shapefile made following the instructions here:
with cl:
topojson -o 'USApuma.json' --shapefile-encoding utf8 --id-property=+GEOID10 -p GINI,+STATEFP10,+GEOID10 -- 'usaetest.shp'
then read in with readLines().
Eventually trying to throw this into a shiny app. Here's some examples I've been following.
Do you need to use TopoJSON? If not consider using the tigris package (disclosure: I created and maintain the package). It'll get you access to just about any Census geographic dataset you need, and plays nicely with leaflet. Here's a brief example in line with what you are doing. For example, you can get all PUMAs in the continental US with the following code:
library(readr)
library(tigris)
library(leaflet)
us_states <- unique(fips_codes$state)[1:51]
continental_states <- us_states[!us_states %in% c("AK", "HI")]
pumas_list <- lapply(continental_states, function(x) {
pumas(state = x, cb = TRUE)
})
us_pumas <- rbind_tigris(pumas_list)
I've generated a sample dataset that measures PUMA median household income for this example; the geo_join function from the tigris package can merge the dataset to the spatial data frame us_pumas:
puma_income <- read_csv('http://personal.tcu.edu/kylewalker/data/puma_income.csv')
joined_pumas <- geo_join(us_pumas, puma_income, 'GEOID10', 'GEOID')
We can then plot with Leaflet:
pal <- colorQuantile(palette = 'YlOrRd', domain = joined_pumas$hhincome, n = 7)
leaflet(joined_pumas) %>%
addProviderTiles('CartoDB.Positron') %>%
addPolygons(weight = 0.5, fillColor = ~pal(hhincome),
color = 'lightgrey', fillOpacity = 0.75,
smoothFactor = 0.2) %>%
addLegend(pal = pal,
values = joined_pumas$hhincome)
If you are planning to build a Shiny app, I'd recommend saving out the PUMAs you obtain from tigris first as a .rda file and reading it in with your Shiny script so you don't have to rbind_tigris every time.
I'm trying to follow the example in the link below to create a map with all the markers
Tutorial: How to put dots on a Leaflet map with R
The source file is below
https://www.dropbox.com/s/az1yolknqwoxhb4/test_file.csv?dl=0
And the code that I tried
library(dplyr)
library(leaflet)
test_map <- read.csv("test_file.csv", header = TRUE, stringsAsFactors = FALSE)
m <- leaflet(test_map) %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
attribution='Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap')
m %>% setView()
m %>% addCircles(~long, ~lat,
popup=test_map$index,
weight = 3,
color="#ffa500", stroke = TRUE, fillOpacity = 0.8)
I was able to create the map
However, the map only shows a fraction of points, since the data I have has locations all over Canada. When I tried to sub-select a city say like Toronto then some of the missing points shows up.
I'm not sure if i'm doing anything wrong or if this is a bug.I wonder if there's anyway for me to fix this problem or is there an alternative way to achieve a similar map?
Thank you :)
There are NA values in test_map variable.
add
test_map <- na.omit(test_map)
after reading csv.
By this method i have more markers than your image.