SpatialPolygonDataFrame plotting using ggplot

你。 提交于 2019-12-07 16:15:17

问题


I am having a shape file for the greater London area. I use the readShapePoly function from the maptools package to load it in R as a SpatialPolygonDataFrame .

I want to the plot those polygons .. Which I have already done by using the basic of plot function in R. The output looks as shown in this image:

Now, I am trying to plot the same shape file using ggplot2 but it doesn't work with me. I am getting some weird lines in the graph as shown blew:

The code I used was :

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')

where projString is the projection string describing the projection used for the input shape file.


回答1:


You need to add an additional aesthetic, group. Assuming the polygon id is called ID, the synatx will look like:

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



回答2:


Alternatively, is good to transition to the sf package which is integrated nicely with ggplot2 via the geom_sf geometry.

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()

Created on 2019-05-20 by the reprex package (v0.2.1)



来源:https://stackoverflow.com/questions/18174703/spatialpolygondataframe-plotting-using-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!