Reputation: 53
I'm attempting to plot a SpatialLinesDataFrame using the R package tmap. However I keep getting this error message:
Error in CPL_geos_is_empty(st_geometry(x)): Evaluation error: IllegalArgumentException: point array must contain 0 or >1 elements.
I first tried plotting the "sp" object using tmap. I then converted the sp object to an "sf" object and still got the same error message. I did a little bit of Googling and I think it might have something to do with the fact that the lines are not all fully connected in the SpatialLinesDataFrame.
So I subset out a group of lines that were connected and it plotted just fine using tmap.
I placed the shapefiles that I used here here on my Github.
EX1812_SPB_combined
is the shapefile that contains the lines that are not connected and is the one that does not plot using tmap and gives me the above error. It plots just fine if I use R's base plot().
EX1812_SBP_combined_section
is the shapefile I subset from the former that contains connected lines. This one plots fine using tmap.
Here is what I what I was trying to do:
Attempt 1: Try plotting the shapefile
library(tmap)
library(sf)
library(rgdal)
library(sp)
# read in shapefile as SpatialLinesDataFrame
sbp <- readOGR(dsn = "file/path", layer = "EX1812_SPB_combined")
# plot using tmap
# this does not work and gives me the aforementioned error
tm_shape(sbp) + tm_lines()
Attempt 2: Convert SpatialLinesDataFrame to sf object
# convert to sf
sbp_sf <- st_as_sf(sbp) + st_set_crs(4326)
# plot using tmap
# this also does not work and gives me the same error
tm_shape(sbp_sf) + tm_lines()
Attempt 3: Read in the shapefile where the lines are connected and plot
# read in shapefile as SpatialLinesDataFrame
sbp_connect <- readOGR(dsn = "file/path", layer = "EX1812_SBP_combined_section")
# plot using tmap
# this works
tm_shape(sbp_connect) + tm_lines()
I just want to plot the entire SpatialLinesDataFrame even if the lines are disconnected. Is there a way around this using tmap? Or am I missing some larger problem?
Upvotes: 4
Views: 2255
Reputation: 8719
I have only a little understanding of your dataset, so I have no way of making sure.
But I suggest the following code; it is based on repairing invalid geometry in sf format by using st_make_valid()
call from the lwgeom package (a companion of sorts of sf).
If nothing else it ends up with a plausible looking plot:
library(sf)
library(lwgeom)
library(dplyr)
library(tmap)
sbp <- sf::st_read("EX1812_SPB_combined.shp") %>%
lwgeom::st_make_valid() %>%
sf::st_set_crs(4326) # always a sensible default (WGS84)
tm_shape(sbp) + tm_lines()
Upvotes: 3