Skip to content

Instantly share code, notes, and snippets.

@hrbrmstr
Last active November 12, 2018 13:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hrbrmstr/e3d0dc87eaacf7bbece7 to your computer and use it in GitHub Desktop.
Save hrbrmstr/e3d0dc87eaacf7bbece7 to your computer and use it in GitHub Desktop.
Swiss Cantons - R version of http://bl.ocks.org/mbostock/4207744
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
library(rgeos)
library(rgdal) # needs gdal > 1.11.0
library(ggplot2)
# map theme
devtools::source_gist("https://gist.github.com/hrbrmstr/33baa3a79c5cfef0f6df")
map = readOGR("readme-swiss.json", "cantons")
map_df <- fortify(map)
# create mapping for id # to name since "region=" won't work
dat <- data.frame(id=0:(length(map@data$name)-1), canton=map@data$name)
map_df <- merge(map_df, dat, by="id")
# find canton centers
centers <- data.frame(gCentroid(map, byid=TRUE))
centers$canton <- dat$canton
# make a map!
gg <- ggplot()
gg <- gg + geom_map(data=map_df, map=map_df,
aes(map_id=id, x=long, y=lat, group=group),
color="#ffffff", fill="#bbbbbb", size=0.25)
# gg <- gg + geom_point(data=centers, aes(x=x, y=y))
gg <- gg + geom_text(data=centers, aes(label=canton, x=x, y=y), size=3)
gg <- gg + coord_map()
gg <- gg + labs(x="", y="", title="Swiss Cantons")
gg <- gg + theme_map()
gg
ggsave("cantons.svg", gg, width=9, height=6)
@salim-b
Copy link

salim-b commented Nov 12, 2017

just a reminder: plotting the data in readme-swiss.json doesn't correctly display the cantons AI and AR because they get "overwritten" by SG. you have to reorder the data to correct this:

library(dplyr)

map_df$id %<>% recode(`16` = 14L,
                      `15` = 16L,
                      `14` = 15L)

map_df$group %<>% recode("16.1" = "14.1",
                         "16.2" = "14.2",
                         "16.3" = "14.3",
                         "16.4" = "14.4",
                         "15.1" = "16.1",
                         "15.2" = "16.2",
                         "15.3" = "16.3",
                         "14.1" = "15.1")

Additionally I'd recommend to remove all the duplicate rows to tremendously speed up plotting :) my fault, there are no duplicates in the readme-swiss.json; instead I've happened to produce them by myself 🙈

library(magrittr)

map_df %<>% .[!duplicated(.), ]

@hrbrmstr
Copy link
Author

hrbrmstr commented Apr 8, 2018

thx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment