使用网络抓取的数据在 R 中进行映射

Mapping in R with Web Scraped Data

我正在尝试在世界地图上可视化来自维基百科的 Polity IV 系列数据集的 table。

取出一些变量后,我希望通过颜色编码可视化国家及其政权类型(编码为 Polity 数据集 IV 类别)。网页上有一个世界地图可视化作为我复制的基础。

我查阅了此 website 的文档,看来我需要将我的数据集与打包的地理数据结合起来。虽然,我不确定该怎么做。

输入:

library(rvest)
library(dplyr)

polity <- read_html("https://en.wikipedia.org/wiki/Polity_data_series")

table <- polity %>% html_table(fill=T)

second_table <- table[[2]]
second_table <- second_table[c(1,5)]

polity <- second_table

library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggplot2)

world <- ne_countries(scale = "medium", returnclass = "sf")

ggplot(data = world) +
    geom_sf() +
    xlab("Longitude") + ylab("Latitude") +
    ggtitle("World map", subtitle = paste0("(", length(unique(world$NAME)), " countries)"))

这是否符合您的要求?

world2 <- left_join(world, polity,
                    by = c("name" = "Country"))

ggplot(data = world2) +
  geom_sf(aes(fill = `Polity datasets IV category`)) +
  xlab("Longitude") +
  ylab("Latitude")