How can I keep polygons\'s information after shapefile? Let me try to explain:
I have a shapefile with this data:
> head(mapa@data)
ID C
Assumption that data$CD_GEOCODI and shape@data are both unique for each row. Below is a better and simpler answer:
library(dplyr)
library(ggplot2)
# fortify the shape file
map.df <- fortify(shape, region ="CD_GEOCODI")
# change data$CD_GEOCODI to character, as shp.df$CD_GEOCODI is of character class.
data <- data %>% mutate(data, CD_GEOCODI = as.character(CD_GEOCODI))
# merge data
map.df <- left_join(map.df, data, by=c('id'='CD_GEOCODI'))
Since you did not provide your shapefile or data, it's impossible to test, but something like this should work:
# not tested...
library(plyr) # for join(...)
library(rgdal) # for readOGR(...)
library(ggplot2) # for fortify(...)
mapa <- readOGR(dsn=".",layer="shapefile name w/o .shp extension")
map@data$id <- rownames(mapa@data)
mapa@data <- join(mapa@data, data, by="CD_GEOCODI")
mapa.df <- fortify(mapa)
mapa.df <- join(mapa.df,mapa@data, by="id")
ggplot(mapa.df, aes(x=long, y=lat, group=group))+
geom_polygon(aes(fill=Population))+
coord_fixed()
Maybe this is a slightly simpler solution
library(dplyr)
library(ggplot2)
# fortify the shape file
map.df <- fortify(shape, region ="CD_GEOCODI")
# merge data
map.df <- left_join(map.df, data, by=c('id'='CD_GEOCODI'))
I came across the same problem and was able to achieve the desired results using slightly different approach.
I have used the following code to read the shapes:
shps <- maptools::readShapePoly(fn = file.path("file",
"path",
"no extension"),
# Column with unique IDs
IDvar = "geoID")
and subsequently fortified the objet using the code:
shpsFort <- ggplot2::fortify(model = shps)
This created a data.frame object with the id
value corresponding to the column passed in IDvar = "geoID"
. Adding any other data could be simply addressed via ordinary merge
command.