Skip to content

Instantly share code, notes, and snippets.

@reinholdsson
Last active August 29, 2015 14:21
Show Gist options
  • Save reinholdsson/16c4a8d3b14b9410dac9 to your computer and use it in GitHub Desktop.
Save reinholdsson/16c4a8d3b14b9410dac9 to your computer and use it in GitHub Desktop.
OLD: kolada with maps example (see swemaps package instead)
library(ggplot2)
library(rkolada)
library(stringr)
# Get coordinates/polygons data
prepare_map_data <- function(x) {
poly <- read.csv('https://db.tt/rexpDv4U') # see also 'https://db.tt/lNz7K3KD' for regions/lnkod
poly$municipality.id <- str_pad(poly$knkod, 4, 'left', '0')
res <- merge(poly, x, by = 'municipality.id')
res[order(res$order),] # it must be sorted by the 'order' column, or else the map fail!
}
## Example 1 ###
# Get data from Kolada
a <- rkolada::rkolada()
x <- a$values('N00941', year = 2010) # make sure "kpi.municipality_type == 'K'"
# Plot it!
ggplot(prepare_map_data(x), aes_string('long', 'lat', group = 'municipality.id', fill = 'value')) +
geom_polygon() +
coord_equal()
### Example 2 ###
y <- a$values('N00941', c('1440', '0604', '2505', '2084'), year = 2010, all.cols = T)
ggplot(prepare_map_data(y), aes_string('long', 'lat', group = 'municipality.id', fill = 'value')) +
geom_polygon() +
coord_equal() +
facet_wrap(~municipality.title, scales = 'free', ncol = 2) +
theme_bw()
### Example 3 ###
library(leaflet)
library(rgdal)
z <- a$values('N00941', year = 2010, all.cols = T)
z2 <- prepare_map_data(z)
# TODO:
# - Move conversion to function OR rewrite map data (e.g. ggplot_lat, leaflet_lat)
# https://sites.google.com/a/lakeheadu.ca/yong-luo/blog/convert-utm-to-longlat-in-r
utmcoor<-SpatialPoints(cbind(z2$long,z2$lat), proj4string=CRS("+proj=utm +zone=33"))
longlatcoor<-spTransform(utmcoor,CRS("+proj=longlat"))
z2$long <- longlatcoor@coords[,1]
z2$lat <- longlatcoor@coords[,2]
L <- data.table(z2)
m = leaflet() %>% addTiles()
for (i in unique(L$municipality.id)) {
j <- L[municipality.id == i]
print(i)
m <- m %>% addPolygons(j$long, j$lat, color = 'red', weight = 1)
}
m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment