【问题标题】:Error with function fortify of ggplot2ggplot2的功能强化错误
【发布时间】:2013-06-21 22:16:49
【问题描述】:

我在 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 Format the ggplot2 map 中找到的 shapefile,数据为 https://docs.google.com/file/d/0B_coFit6AovfcEFkbHBjZEJaQ1E/edit

【问题讨论】:

    标签: r ggplot2 gis


    【解决方案1】:

    这是一种解决方法,但是如果您将 UF 列复制为 id 列,如示例 wiki 中的我的 cmets 在数据准备下显示的那样,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:当我尝试强化 readOGR 读取的 shapefile 并指定 region="UF" 时,您的 shape 文件上的拓扑存在错误,根据错误消息判断您有 2 个重叠区域。 #Error: TopologyException: 发现 LINESTRING (-48.5843 -27.9514, -48.5889 -27.9956) 和 LINESTRING (-48.5889 -27.9944, -48.5844 -28.066) 在 -48.588852991466581 -27.995432649.3s
    猜你喜欢
    • 1970-01-01
    • 2015-01-27
    • 2021-10-18
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多