Error with function fortify of ggplot2

2019-06-24 10:51发布

I am getting this error with the method fortify in ggplot2:

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘proj4string’ for signature ‘"NULL"’

The code is the following:

> library(maptools)
> gpclibPermit()
> library(ggplot2)
> library(rgdal)
> library(rgeos)
> library(ggmap)
> brMap <- readShapePoly("Google/BRASIL.shp")
> brMapDF <- fortify(brMap)
# This actually works

# But this don´t

> brMapDF <- fortify(brMap, region="UF")

Error in (function (classes, fdef, mtable)  : 
            unable to find an inherited method for function ‘proj4string’ for signature ‘"NULL"’

This happens with all the shapefiles that I have, so I tried (in the code above) with a shapefile that I found in stackoverflow Format the ggplot2 map, the data is https://docs.google.com/file/d/0B_coFit6AovfcEFkbHBjZEJaQ1E/edit

标签: r ggplot2 gis
1条回答
forever°为你锁心
2楼-- · 2019-06-24 11:24

It's a bit of a workaround, but if you duplicate the UF column as an id column as shown in the example wiki from my comments under data preparation, the defaults for fortify will use the first column in the spatial data frame to separate out the polygons accordingly while adding the names under the id column.

library(maptools)
library(ggplot2)
library(sp)
library(rgdal)
library(rgeos)

brMap <- readShapePoly("Google/BRASIL", IDvar = "UF",
    proj4string = CRS("+init=epsg:4236"), repair = TRUE, verbose = TRUE)
brMap@data$id <- brMap@data$UF
brMapDF <- fortify(brMap)

The resulting structure for brMapDF is then:

'data.frame':   9316 obs. of  7 variables:
 $ long : num  -68.6 -68.7 -68.8 -68.8 -68.9 ...
 $ lat  : num  -11.1 -11.2 -11.2 -11.1 -11.1 ...
 $ order: int  1 2 3 4 5 6 7 8 9 10 ...
 $ hole : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ piece: Factor w/ 37 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ group: Factor w/ 81 levels "AC.1","AL.1",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ id   : chr  "AC" "AC" "AC" "AC" ...
查看更多
登录 后发表回答