Skip to content

Instantly share code, notes, and snippets.

@kzktmr
Last active December 4, 2016 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kzktmr/89049df857b1eff34e959416ea2146f4 to your computer and use it in GitHub Desktop.
Save kzktmr/89049df857b1eff34e959416ea2146f4 to your computer and use it in GitHub Desktop.
Draw a very simple prefectural choropleth map of Japan with ggplot
ggJapanPrefecturesMap <- function (col = "white", fill = NULL, inset = TRUE, silent = FALSE, ...)
{
require(Nippon)
if(require(ggplot2)){
require(foreign)
m <- readShapePoly(system.file("shapes/jpn.shp", package = "Nippon")[1],
proj4string = CRS("+proj=longlat +datum=WGS84"))
if (inset) {
xy.okinawa <- m@polygons[[47]]@Polygons[[1]]@coords
xy.okinawa[, 1] <- xy.okinawa[, 1] + 7
xy.okinawa[, 2] <- xy.okinawa[, 2] + 14
m@polygons[[47]]@Polygons[[1]]@coords <- xy.okinawa
labpt <- m@polygons[[47]]@labpt
labpt[1] <- labpt[1] + 7
labpt[2] <- labpt[2] + 14
m@polygons[[47]]@labpt <- labpt
m@bbox[1, 1] <- 130
m@bbox[2, 1] <- 31
}
fm <- fortify(m)
fm$id <- as.numeric(fm$id)
d <- read.dbf(system.file("shapes/jpn.dbf", package="Nippon"), as.is=TRUE)
d$id <- as.numeric(d$SP_ID) - 1
g <- ggplot(d) + theme_bw()
if(is.null(fill)){
col <- head(rep(col, ceiling(47 / length(col))), 47)
g <- g + geom_map(map = fm, aes(map_id = id), fill = col, colour = "black", size = 0.2)
}else{
g <- g + geom_map(map = fm, aes(map_id = id, fill = fill), colour = "black", size = 0.2)
}
g <- g + expand_limits(x = fm$long, y = fm$lat) + coord_map() +
theme(axis.title = element_blank())
if (inset) {
g <- g + geom_line(data = data.frame(long = c(132, 135, 137, 137), lat = c(38, 38, 40, 43)),
mapping = aes(x = long, y = lat), colour = "black", size = 0.2)
}
if(!silent)plot(g)
coord <- as.data.frame(coordinates(m))
colnames(coord) <- c("long", "lat")
return(invisible(list(plot = g, coordinates = coord)))
}else{
return(JapanPrefecturesMap(col = col, inset = inset, ...))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment