Question

I have 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:

plot of London

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

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.

Was it helpful?

Solution

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top