Search code examples
rgeometrygisqgisr-sf

Cannot plot sf linestring in R: Error in CPL_geos_is_empty(st_geometry(x))


I have hurricane track points which I converted to lines in QGIS:

https://i.sstatic.net/Gtt61.png

https://i.sstatic.net/6z8MO.png

I have both saved as shapefiles and load them into R using the sf package. The points will plot using the standard plot() function, but the lines will not.

I am encountering the error:

plot(hurricane_paths)
Error in CPL_geos_is_empty(st_geometry(x)) : 
     Evaluation error: IllegalArgumentException: point array must contain 0 or >1 elements.

I have the same error when I use plot(st_geometry(hurricane_paths))

R definitely loads in the geometry, though:

> hurricane_paths
Simple feature collection with 1410 features and 5 fields
geometry type:  LINESTRING
dimension:      XY
bbox:           xmin: -179.9 ymin: -4.9 xmax: 8 ymax: 70.7
epsg (SRID):    4269
proj4string:    +proj=longlat +datum=NAD83 +no_defs
First 10 features:
             N.A begin  end Year           N.A_1                       geometry
1  1976143N24271  <NA> <NA> 1976 SUBTROP:UNNAMED LINESTRING (-89 24, -89.6 2...
2  1976155N11265  <NA> <NA> 1976         ANNETTE LINESTRING (-95 11.4, -95.2...
3  1976159N27281  <NA> <NA> 1976         UNNAMED LINESTRING (-79 26.8, -78.5...

And st_geometry(hurricane_paths) returns

Geometry set for 1410 features 
geometry type:  LINESTRING
dimension:      XY
bbox:           xmin: -179.9 ymin: -4.9 xmax: 8 ymax: 70.7
epsg (SRID):    4269
proj4string:    +proj=longlat +datum=NAD83 +no_defs
First 5 geometries:
LINESTRING (-89 24, -89.6 24.8, -90 25.4, -90.5...
LINESTRING (-95 11.4, -95.2 11.7, -95.3 12.1, -...
LINESTRING (-79 26.8, -78.5 28, -78.1 29.2, -77...
LINESTRING (-81 26.5, -78.5 28.2, -76.2 30, -73...
LINESTRING (-103 16, -104.1 15.8, -105.1 15.8, ...

I already checked for NAs in my geometry column:

> which(is.na(hurricane_paths$geometry)==T)
integer(0)

plot_sf() does not return any error message, but it returns a blank screen in the plots pane, so that's a no-go either.

But ggplot2 is great, and returns a graphic, no problem:

> ggplot() + 
+   geom_sf(data = hurricane_paths)

Mapview also is fine: > mapview::mapview(hurricane_paths)

But the basic plot() function remains stubborn. What could the problem be?


Solution

  • I was having a problem just like yours and it seems that the problem is in the conversion from points to linestring. Following a solution found in the thread Create Multilines from Points, grouped by ID with sf package, you may have to use

    summarise(do_union = FALSE) %>%
    st_cast("LINESTRING")
    

    before transforming your point dataset to a linestring.

    I hope it helps.