I´m having problems when combining a map from Google Map Api, with a map constructed with geom_polygon
from ggplot2
. When I plot each map on their own, nothing weird shows up, but when I do combine them, some lines(straight) appear, messing up the boundaries I intend to highlight.
1) The data I´m using to construct the polygos with the black borders comes from this link. The exact url of the file is in my code below. Sometimes it is necessary to unzip the file manually, therefore the code below for downloading the data may not work:
path <- getwd()
fileName <- "R05.zip"
if (!file.exists(fileName)) {
urlFile = "http://www.censo2017.cl/wp-content/uploads/2016/12/R05.zip"
download(urlFile, dest = "./R05.zip", mode ="wb")
}
if (!dir.exists("./R05")) {
unzip("R05.zip")
}
2) Then I load the shapefile with which I´ll construct the polygons.
distritos <- readOGR( dsn= paste(getwd(), "/R05", sep = ""),
layer="Distritos_Censales",
encoding = "UTF-8", stringsAsFactors = FALSE)
3) And select the administrative division I´m interested in
distritos <- distritos[distritos@data$DESC_COMUN=="QUILPUÉ", ]
4) And then the districts (polygons) I´m interested in:
distritos <- distritos[distritos@data$DESC_DISTR=="EL RETIRO" |
distritos@data$DESC_DISTR=="BELLOTO NORTE" |
distritos@data$DESC_DISTR=="VALENCIA" |
distritos@data$DESC_DISTR=="MENA" |
distritos@data$DESC_DISTR=="BELLOTO SUR" |
distritos@data$DESC_DISTR=="ALTO QUILPUÉ" |
distritos@data$DESC_DISTR=="EL SAUCE", ]
5) Construct the base map from the boundaries of distritos
. For that,
I use the function to get the center of a map from this StackOverflow question
bbox(distritos)
MapCenter <- function(x1, y1, x2, y2){
center.x <- x1 + ((x2 - x1) / 2)
center.y <- y1 + ((y2 - y1) / 2)
center <- c(center.x, center.y)
center
}
mcdistritos <- MapCenter(bbox(distritos)[1,1], bbox(distritos)[2,1],
bbox(distritos)[1,2], bbox(distritos)[2,2])
basemap <- get_googlemap(mcdistritos, zoom = 13,
maptype = "roadmap",
color = "bw",
style = "feature:administrative|element:labels|visibility:off")
basemap <- ggmap(basemap , extent = "device")
6) prepare the shapefile data to plot it with ggplot2
distritos.fort <- fortify(distritos, region = "DESC_DISTR")
7) Plot together both maps
basemap +
geom_polygon(data = distritos.fort,
aes(x = long, y = lat),
colour = "black",
fill = NA) + coord_map()
I tried by zooming out the base map, in case the polygon boundaries were messed up cause they didn´t fit in the base map, but I got the same result, just a smaller map. Does anyone know how to fix it?
distritos@data$DESC_DISTR=="EL RETIRO" | distritos@data$DESC_DISTR=="BELLOTO NORTE" | distritos@data$DESC_DISTR=="VALENCIA" | distritos@data$DESC_DISTR=="MENA" |...
with something much shorter, likedisitros@data$DESC_DISTR %in% c("EL RETIRO", "BELLOTO NORTE", "VALENCIA", "MENA", ...)
– Gregor Thomas