【问题标题】:SpatialPolygonDataFrame plotting using ggplot使用 ggplot 绘制 SpatialPolygonDataFrame
【发布时间】:2023-03-13 22:29:01
【问题描述】:

我有一个大伦敦地区的形状文件。我使用 maptools 包中的 readShapePoly 函数将其作为 SpatialPolygonDataFrame 加载到 R 中。

我想绘制那些多边形 .. 我已经通过使用 R 中的 plot 函数的基本功能完成了。 输出如下图所示:

现在,我正在尝试使用 ggplot2 绘制相同的形状文件,但它对我不起作用。 我在图中得到了一些奇怪的线条,如下所示:

我使用的代码是:

london.wards <- readShapePoly("~/TD/london_wards2013/london_wards2013.shp"
                          , proj4string=CRS(projString))
wards.count <- nrow(london.wards@data)
# assign id for each lsoa

london.wards@data$id <- 1:wards.count
wards.fort <- fortify(london.wards, region='id')
ggplot(wards.fort, aes(long, lat)) + geom_polygon(colour='black', fill='white')

其中 projString 是描述用于输入形状文件的投影的投影字符串。

【问题讨论】:

    标签: r ggplot2 gis shapefile maptools


    【解决方案1】:

    您需要添加额外的美学,group。假设多边形 id 被称为 ID,则 synatx 将如下所示:

    ggplot(wards.fort, aes(x = long, y = lat, group = ID)) + 
       geom_polygon(colour='black', fill='white')
    

    【讨论】:

      【解决方案2】:

      或者,最好过渡到sf 包,该包通过geom_sf 几何结构很好地与ggplot2 集成。

      library(sf)
      library(ggplot2)
      
      # Download the London shapefile.
      # Links at Statistical GIS Boundary Files for London:
      # https://data.london.gov.uk/dataset/statistical-gis-boundary-files-london
      dataset_url <- "https://data.london.gov.uk/download/statistical-gis-boundary-files-london/b381c92b-9120-45c6-b97e-0f7adc567dd2/London-wards-2014.zip"
      download.file(dataset_url, destfile = "London-wards-2014.zip")
      unzip("London-wards-2014.zip", exdir = "London-wards-2014")
      
      # Read the shapefile
      polys <- st_read("./London-wards-2014/London-wards-2014 (1)/London-wards-2014_ESRI/London_Ward.shp")
      #> Reading layer `London_Ward' from data source `~\London-wards-2014\London-wards-2014 (1)\London-wards-2014_ESRI\London_Ward.shp' using driver `ESRI Shapefile'
      #> Simple feature collection with 654 features and 7 fields
      #> geometry type:  POLYGON
      #> dimension:      XY
      #> bbox:           xmin: 503568.2 ymin: 155850.8 xmax: 561957.5 ymax: 200933.9
      #> epsg (SRID):    NA
      #> proj4string:    +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.999601272 +x_0=400000 +y_0=-100000 +datum=OSGB36 +units=m +no_defs
      
      # Fast plot/map
      ggplot(polys) +
        geom_sf()
      

      reprex package (v0.2.1) 于 2019 年 5 月 20 日创建

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-07
        • 1970-01-01
        • 2013-11-14
        相关资源
        最近更新 更多