Petr
Petr

Reputation: 1817

spatial network plot using ggplot

I would like to reproduce plot of spatial dependency of regions in ggplot2 rather then using basic plot in R

I provided reproduceble example in code below:

I followed example: Plotting neighborhoods network to a ggplot maps

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

URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_CZE_1_sp.rds"
data <- readRDS(url(URL))

ggplot() + 
  geom_polygon(data = data, aes(x=long, y = lat, group = group), color = "black", fill = F)

cns <- knearneigh(coordinates(data), k = 3, longlat=T)
scnsn <- knn2nb(cns, row.names = NULL, sym = T)
cns
scnsn
cS <- nb2listw(scnsn)
summary(cS)

# Plot of regions and k-nn neighthorhours matrix

plot(data)
plot(cS, coordinates(data), add = T)

I am asking how to reproduce Plot of regions and k-nn neighthorhours matrix using ggplot.

I know we have to retrive each point input and then use geom_segment, however I dont know how to retrive it from cS object.

Upvotes: 0

Views: 318

Answers (1)

dc37
dc37

Reputation: 16178

The other SO post you are refering contains all steps you need to follow to get your plot (thanks to the great answer from @StupidWolf).

Basically, you need to extract the different segment using:

1) Transform coordinates of data in a dataframe, it will facilitate its use later:

data_df <- data.frame(coordinates(data))
colnames(data_df) <- c("long", "lat")

This data_df contains now all x,y values for plotting points.

2) Now, we can retrieve segments informations from the cS object using:

n = length(attributes(cS$neighbours)$region.id)
DA = data.frame(
  from = rep(1:n,sapply(cS$neighbours,length)),
  to = unlist(cS$neighbours),
  weight = unlist(cS$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")

In the DA dataframe, you have all informations required to draw each segments

3) Finally, you can put plot every parts:

ggplot(data, aes(x = long, y =lat))+
  geom_polygon(aes(group = group), color = "black", fill = FALSE)+
  geom_point(data = data_df, aes(x= long, y = lat), size = 1)+
  geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5)

enter image description here

Again, the solution provided by @StupidWolf was pretty well written and understandable, so I don't know why you were not able to reproduce it.

Upvotes: 3

Related Questions