Make a choropleth from a non-highmap-collection map

杀马特。学长 韩版系。学妹 提交于 2019-12-11 14:09:13

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/56638880/make-a-choropleth-from-a-non-highmap-collection-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!