TransWikia.com

Spatial neighbors in ggplot2

Geographic Information Systems Asked on March 31, 2021

I’m trying to make a space plot with ggplot() as indicated here, but I’m having trouble using the nb2lines() function.

.shp files are here

Error in if (!is.na(projargs) && !nzchar(projargs)) projargs <- NA_character_ : missing value where TRUE/FALSE is required

while using plot() if it works for me, how could I fix it?

ec = st_read("nxparroquias.shp") %>% 
  sf::st_transform('+init=epsg:4326')

peta_nb <- poly2nb(ec)
plot(ec, col="white", border="grey")
plot(peta_nb, coordinates(as_Spatial(ec.sp2)), col="red", add=TRUE) 

enter image description here

What I got

nc_sp2 <- as(ec, 'Spatial')
neighbors <- poly2nb(nc_sp)
neighbors_sf <- as(nb2lines(neighbors, coords = coordinates(nc_sp2)), 'sf')
neighbors_sf <- st_set_crs(neighbors_sf, st_crs(ec))

nc_sp <- as(ec, 'Spatial') 
neighbors <- poly2nb(nc_sp)
neighbors_sf <- as(nb2lines(neighbors, coords = coordinates(nc_sp2)), 'sf')

#Error in if (!is.na(projargs) && !nzchar(projargs)) projargs <- NA_character_ : missing value where TRUE/FALSE is required

#neighbors_sf <- st_set_crs(neighbors_sf, st_crs(ec))

#ggplot(nc_sp) + 
#  geom_sf(fill = 'salmon', color = 'white') +
#  geom_sf(data = neighbors_sf) +
#  theme_minimal() +
#  ylab("Latitude") +
#  xlab("Longitude")

One Answer

You are mixing sp and sfobjects, in your code, nc_spis a spobject and you are trying to use geom_sf to plot it, which is a method for sf objects; this code works on my computer:

library(sf)
library(spdep)
library(ggplot2)

ec = st_read("nxparroquias.shp") %>% 
  sf::st_transform(4326) # function accepts the EPSG code number

nc_sp <- as(ec, 'Spatial') # coords argument uses sp style
neighbors <- poly2nb(nc_sp) 

neighbors_sf <- as(nb2lines(neighbors, coords = coordinates(nc_sp),
                        proj4string = CRS("+proj=longlat +datum=WGS84")), 'sf')

    
ggplot(ec) + # the sf object
    geom_sf(fill = 'salmon', color = 'white') +
    geom_sf(data = neighbors_sf) +
    theme_minimal() +
    ylab("Latitude") +
    xlab("Longitude")

enter image description here

Correct answer by Elio Diaz on March 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP