Search code examples
rspatialshapefileterra

R terra plot vector error subscript out of bounds and no legend or axes


I import a vector:

library(terra)
v <- vect("my file")
plot(v)

works fine

plot(v,1)

returns

Error in g[[i]][[j]] : subscript out of bounds

and then successfully plots v, 1 as expected, but there are no axes and no legend available, I don't get a legend even when doing things like

plot(v,1, plg=list("topleft"))

I am not sure where to begin the trouble shooting?

The .shp file doesn't seem broken, I have check validity and fixed geometries in qgis and .. don't know which way to look now.


Solution

  • This works for me

    library(terra)
    #terra 1.6.41
    v <- vect( system.file("ex/lux.shp", package="terra") )
    
    plot(v, 2)
    

    or the more expressive

    plot(v, "NAME_1")
    

    Later:

    With your file (send to me privately) I had the same error. I fixed it in "terra" version 1.6-48 (you can install the development version with install.packages('terra', repos='https://rspatial.r-universe.dev').

    This was caused by empty geometries (polygons). You can see which geometries are empty with emptyGeoms

    emptyGeoms(v)
    # [1] 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554
    #[13] 10556 10558 10559 10560 10561 10562 10563 10564 10565
    

    And you can remove them with na.omit

    nrow(v)
    #[1] 12694
    vv <- na.omit(v, geom=T)
    nrow(vv)
    #[1] 12673