代码之家  ›  专栏  ›  技术社区  ›  JaElf

在R中使用ggmap打印多边形

  •  0
  • JaElf  · 技术社区  · 7 年前

    我想在地图上画一个多边形。为此,我目前使用ggmap,但它不允许我这样做,总是给我一条错误消息:

    Fehler:ggplot2二进制运算符的非数值参数

    我的代码如下所示:

    > library(rgdal)
    > library(geojsonio)
    > library(sp)
    > library(maps)
    > library(ggmap)
    > library(maptools)
    
    > data_file <- "/home/jan/Downloads/map.geojson"
    
    > data_json <- geojson_read(data_file, what = "sp")
    
    > plot(data_json, usePolypath = FALSE)
    
    > mapImage <- ggmap(get_googlemap(c(lon = -118.243683, lat = 34.052235), scale = 1, 
    +                                 zoom = 7), extent = "normal")
    Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=34.052235,-118.243683&zoom=7&size=640x640&scale=1&maptype=terrain&sensor=false
    
    > dat <- as.data.frame(data_json)
    
    > names(data)[1:2] <- c("lon","lat")
    
    > print(mapImage)+
    +   geom_polygon(data = dat, aes(lon, lat), colour="red", fill="red")
    
    Fehler in print(mapImage) + geom_polygon(data = dat, aes(lon, lat), colour = "red",  : 
      nicht-numerisches Argument für binären Operator
    

    但如果我这样做了

    > dat2 <- as.numeric(dat)
    
    > print(mapImage)+
    +   geom_polygon(data = dat2, aes(lon, lat), colour="red", fill="red")
    Fehler: ggplot2 doesn't know how to deal with data of class numeric
    

    我得到了错误

    ggplot2不知道如何处理numeric类的数据

    PS.Iá对R和编程非常陌生

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Spacedman    7 年前

    这是:

    data_json <- geojson_read(data_file, what = "sp")
    

    返回 sp 类对象,其中 ggplot geom_polygon 无法处理。

    修复程序将运行 fortify 在其上创建一个数据帧 geom\u多边形 可以使用。您尚未向我们提供数据文件,因此我们无法提供确切的代码,但:

    data_file <- system.file("examples", "california.geojson", package = "geojsonio")
    data_json <- geojson_read(data_file, what = "sp")
    fd = fortify(data_json)
    mapImage + geom_polygon(data=fd, aes(x=long,y=lat))
    

    应该给你足够的线索。