How keep information from shapefile after fortify()

后端 未结 4 879
萌比男神i
萌比男神i 2021-02-05 10:06

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         


        
相关标签:
4条回答
  • 2021-02-05 10:18

    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'))
    
    0 讨论(0)
  • 2021-02-05 10:22

    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()
    
    0 讨论(0)
  • 2021-02-05 10:26

    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'))
    
    0 讨论(0)
  • 2021-02-05 10:30

    I came across the same problem and was able to achieve the desired results using slightly different approach.

    Import and fortify

    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)
    

    Results

    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.

    0 讨论(0)
提交回复
热议问题