Created
August 25, 2024 15:49
-
-
Save kzktmr/6da8b5bc973bd7ae1bbd97368998813f to your computer and use it in GitHub Desktop.
Draw a very simple prefectural choropleth map of Japan with ggplot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ggJapanPrefMap <- function (col = NULL, inset = TRUE, ...) | |
| { | |
| require(sf) | |
| require(ggplot2) | |
| if(is.null(col)){ | |
| col <- rep(NULL, 47) | |
| }else{ | |
| if (!is.factor(col)) col <- as.factor(col) | |
| } | |
| shp <- system.file("shapes/jpn.shp", package = "NipponMap")[1] | |
| m <- st_read(shp, quiet = TRUE) |> st_set_crs(4326) |> | |
| st_transform("+proj=aeqd +lat_0=35.65802414 +lon_0=139.74143256 +x_0=0 +y_0=0 +datum=WGS84 +units=km +no_defs") | |
| m$col = col | |
| if (inset) { | |
| m$geometry[[47]] <- m$geometry[[47]] + c(500, 1400) | |
| } | |
| p <- ggplot() + geom_sf(aes(fill = col), data = m) + theme_void() + | |
| guides(fill = guide_legend(position = "inside")) + | |
| scale_fill_discrete() + | |
| theme(legend.title = element_blank(), | |
| legend.margin = margin(0, 0, 0, 0), | |
| legend.position.inside = c(0.9, 0.1), | |
| legend.justification.inside = c(1, 0)) | |
| if (inset) { | |
| p <- p + geom_path(data = data.frame(lon = c(-800, -600, -400, -400), lat = c(200, 200, 400, 600)), | |
| mapping = aes(x = lon, y = lat), color = "black", linewidth = 0.2) | |
| } | |
| return(p) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment