ggplot2的函数fortify出现错误

3

在ggplot2中使用fortify方法时,我遇到了以下错误:

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

对应的代码如下:

> 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"

这种情况发生在我所拥有的所有shapefile文件中,因此我尝试(在上面的代码中)使用在stackoverflow格式化ggplot2地图中找到的一个shapefile文件,数据来源为https://docs.google.com/file/d/0B_coFit6AovfcEFkbHBjZEJaQ1E/edit

1个回答

1

这是一个折中的方法,但是如果您像我在数据准备下的评论中所示的示例维基百科中将UF列复制为ID列,则fortify的默认设置将使用空间数据框中的第一列相应地分隔多边形,并在ID列下添加名称。

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)

brMapDF的结果结构如下:
'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" ...

太好了!现在它可以工作了 :) 谢谢...但是,你能解释一下问题出在哪里吗?为什么原始代码不能工作? - nanounanue
@nanounanue:你的shape文件拓扑存在错误,当我尝试使用readOGR读取文件并指定region="UF"时,根据错误信息显示存在2个重叠区域。#Error: TopologyException: found non-noded intersection between LINESTRING (-48.5843 -27.9514, -48.5889 -27.9956) and LINESTRING (-48.5889 -27.9944, -48.5844 -28.066) at -48.588852991466581 -27.99543264943113。 - user666993

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接