3

我正在做一个项目,其中一小部分正在绘制一张世界地图,其中包含我列表中的 135 个国家/地区。我还有一个清单,说明它们是否已开发。

我如何将它放在世界地图中以不同颜色显示开发状态?

我的数据看起来像这样

Country        Code      Developed
Brazil         BRA         1
Singapore      SIN         3
France         FRA         1
Poland         POL         2

我从另一个问题拍摄了下面的图片,但理想情况下,它看起来像这样,但有更多国家和 3 种不同的颜色。

谢谢

在此处输入图像描述

4

2 回答 2

8

首先你需要安装包:

install.packages(c("cowplot", "googleway", "ggplot2", "ggrepel", 
"ggspatial", "libwgeom", "sf", "rnaturalearth", "rnaturalearthdata")

之后,我们将加载所有地图所需的基本包,即 ggplot2 和 sf。我们还建议为 ggplot2 (theme_bw) 使用经典的暗光主题,它适用于地图:

library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")

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

## [1] "sf"  
## [1] "data.frame"

之后我们可以:

ggplot(data = world) +
    geom_sf()

结果会是这样:

在此处输入图像描述

在它之后,我们可以添加:

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

图形显示如下:

在此处输入图像描述

最后,如果我们想要一些颜色,我们需要这样做:

ggplot(data = world) +
    geom_sf(aes(fill = pop_est)) +
    scale_fill_viridis_c(option = "plasma", trans = "sqrt")

这个例子显示了每个国家的人口。在这个例子中,我们使用“viridis”色盲友好调色板作为颜色渐变(对于等离子变体使用 option = “plasma”),使用人口的平方根(存储在世界对象的变量 POP_EST 中)

在此处输入图像描述

您可以在这里了解更多信息:

https://r-spatial.org/r/2018/10/25/ggplot2-sf.html

https://datavizpyr.com/how-to-make-world-map-with-ggplot2-in-r/

https://slcladal.github.io/maps.html

于 2021-10-19T06:04:13.600 回答
1

如果你想用你自己的数据给它着色,你必须相应地修改world数据框:

library(rnaturalearth)
library(rnaturalearthdata)
library(ggplot2)
library(tidyverse)

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

my_countries <- c("Aruba","Afghanistan", "Morocco", "Canada")

world_modified <- world %>% 
  mutate(my_selection = ifelse(admin %in% my_countries,
                               1, NA))


ggplot(data = world_modified) +
  geom_sf(aes(fill=my_selection)) +
  theme_bw()

reprex 包于 2021-10-19 创建 (v2.0.0 )

于 2021-10-19T06:11:05.210 回答