将邻域网络绘制到ggplot地图

时间:2019-10-24 06:39:05

标签: r ggplot2 spatial

如何将空间网络图插入ggplot

library(rgeos) 
library(rgdal)
library(dplyr)
require(maps)
require(viridis)
library(ggplot2)
library(spdep)


some.eu.countries <- c(
  "Portugal", "Spain", "France", "Switzerland", "Germany",
  "Austria", "Belgium", "UK", "Netherlands",
  "Denmark", "Poland", "Italy", 
  "Croatia", "Slovenia", "Hungary", "Slovakia",
  "Czech republic"
)
# Retrievethe map data

some.eu.maps <- map_data("world", region = some.eu.countries)

# Compute the centroid as the mean longitude and lattitude
region.lab.data <- some.eu.maps %>%
  group_by(region) %>%
  summarise(long = mean(long), lat = mean(lat))

cns <- knearneigh(cbind(region.lab.data$long, region.lab.data$lat), k=3, longlat=T) 
scnsn <- knn2nb(cns, row.names = NULL, sym = T) 
cns
scnsn
cS <- nb2listw(scnsn) 
cS
summary(cS)

# Plotting neighbours network
plot(cS, cbind(region.lab.data$long, region.lab.data$lat))


# Now plotting countries
ggplot(some.eu.maps, aes(x = long, y = lat)) +
  geom_polygon(aes( group = group, fill = region), colour = "black")+
  geom_point(aes(region.lab.data$long, region.lab.data$lat), data = region.lab.data, size = 6)

我想将#Plotting neighbours network插入到# Now plotting countries中,换句话说,我希望了解一些国家/地区,并希望在其中看到邻居的网络。

1 个答案:

答案 0 :(得分:2)

我查看了plot.nb,这是您的nb2listw输出的plot方法,我认为它基本上为您输入之间的所有连接都做了一个细分。

# Now plotting countries
g = ggplot(some.eu.maps, aes(x = long, y = lat)) +
  geom_polygon(aes( group = group, fill = region), colour = "black")+
  geom_point(aes(region.lab.data$long, region.lab.data$lat), data = region.lab.data, size = 6)

# take out the connections from your nb object
# and assign them the lat and long in a dataframe
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,region.lab.data[DA$from,2:3],region.lab.data[DA$to,2:3])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")
#plot it using geom_segment
g + geom_segment(data=DA,aes(xend=long_to,yend=lat_to),size=0.3,alpha=0.5)

这就是我得到的(caveat,我不知道如何处理重量):

enter image description here