[GIS] Can’t plot polygons with R: Invalid number of points in LinearRing found 3 – must be 0 or >= 4

errorggplot2polygonrshapefile

I want to plot a map of my region, with colour filled polygons using R. I have downloaded municipal (lines) and province (polygons) boundaries. I've used SAGA to merge municipal and province shapes to produce new boundaries (polygons) to read and plot with R and ggplot2.

I succesfully plotted the original province (polygons) but failed to plot new boundaries (polygons) with this error message:

Error en createPolygonsComment(p) : IllegalArgumentException:
Invalid number of points in LinearRing found 3 – must be 0 or >= 4

Maybe I made some mistake when merging original polygons and lines to create the new boundaries. Shoud I check shp attributes?

You can find original boundaries here and newly created ones here

EDIT: Added link to data file lineas_limites_municipales_etrs89.dbf

And the original R code I used to plot original boundaries, not working for new ones (see error message above):

require("rgdal")
require("maptools")
require("ggplot2")
require("plyr")

# Reading municipal boundaries

 esp = readOGR(dsn=".", layer="lineas_limite_municipales_etrs89")

 muni=subset(esp, esp$PROV1 == "46" | esp$PROV1 == "12" | esp$PROV1 == "3")
 muni@data$id = rownames(muni@data)
 muni.points = fortify(muni,region="id")
 muni.df = join(muni.points, muni@data, by="id")

# Reading province boundaries

prov = readOGR(dsn=".", layer="poligonos_provincia_etrs89")

pr=subset(prov, prov$CODINE == "46" | prov$CODINE == "12" | prov$CODINE == "03" )
pr@data$id = rownames(pr@data)
pr.points = fortify(pr, region="id")
pr.df = join(pr.points, pr@data, by="id")

ggplot(muni.df) + aes(long,lat,group=group) + geom_path(color="blue") +
coord_equal()+ geom_path(data=pr.df,   aes(x=long,y=lat,group=group),color="red", size=0.5)

Best Answer

The error message is telling that there is at least one corrupt polygon among your data, i.e., a polygon with more than 0 and less than 4 points (0 < points < 4). See Tidying feature geometries with sf for instructions on how to inspect and fix the data, if it is the case.

However, I could not download "original boundaries" (it seems the link is broken), but this is what I got (I think the same as @cengel) with data provided on second link (+ the .dbf file link):

require(rgdal)
require(maptools)
require(ggplot2)
require(plyr)

# Reading municipal boundaries

esp = readOGR(dsn="C:\\...\\boundaries", layer="lineas_limite_municipales_etrs89")

muni=subset(esp, esp$PROV1 == "46" | esp$PROV1 == "12" | esp$PROV1 == "3")
muni@data$id = rownames(muni@data)
muni.points = fortify(muni,region="id")
muni.df = join(muni.points, muni@data, by="id")

#Adapted ggplot function to existing data
ggplot(muni.df) + aes(long,lat,group=group) + geom_path(color="blue") +
coord_equal() + theme_bw()

enter image description here

Related Question