I am working with a state-level shapefile of the United States.


states_sf = get_urbn_map("states", sf = TRUE)

I am plotting the years that a state-level policy went into effect using a color palette in tmap. I would like to indicate the year that a policy was repealed (if relevant) using diagonal lines. Based on this Github thread, I used the hatched.SpatialPolygons function. This works for Arizona: I obtain a layer that I can add to my tmap plot:

AZ = states_sf[which(states_sf$state_abbv =="AZ"),]
AZ_H = hatched.SpatialPolygons(AZ, density=0.0001, angle=45)
st_crs(AZ_H) = st_crs(states_sf)
tm_shape(AZ_H) + tm_lines(col = "black")

Arizona, displayed with diagonal lines

But when I try to do this for Louisiana, as follows, R returns an error:

LA = states_sf[which(states_sf$state_abbv =="LA"),]
LA_H = hatched.SpatialPolygons(LA, density=0.0001, angle=45)

Error in apply(lines.hatch, 1, function(x) Line(cbind(c(x[1], x[3]), c(x[2],  : 
  dim(X) must have a positive length

I thought the error may be due to Louisiana having a less linear boundary than Arizona. But when I tried to smooth the boundary using smooth(), hatched.SpatialPolygons returned the same error message.

Please advise on how to address this error message so that hatched.SpatialPolygons can render a spatial object of diagonal lines filling Louisiana. I am also open to alternative approaches.


It seems like the issue was due to islands in the sf object, not the non-linear style of the object's borders. I used the rmapshaper package and the ms_filter_islands() function to drop islands, and then hatched.SpatialPolygons produced the shapefile of diagonal lines within the state boundary:

LA = states_sf[which(states_sf$state_abbv =="LA"),]
LA2 = ms_filter_islands(LA, min_area = 10000000000)
tm_shape(LA2) + tm_borders()
LA_H = hatched.SpatialPolygons(LA2, density=0.0001, angle=45)
st_crs(LA_H) = st_crs(states_sf)
tm_shape(LA_H) + tm_lines(col = "black")

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.