繁体   English   中英

如何使用 R 绘制世界地图

[英]How to plot a world map using R

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

我如何将它放在世界地图中,为开发状态使用不同的颜色?

我的数据看起来像这样

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

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

谢谢

在此处输入图片说明

首先你需要安装软件包:

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

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

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”色盲友好调色板进行颜色渐变(对于等离子变体,选项=“等离子”),使用人口的平方根(存储在世界对象的变量 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

如果要使用自己的数据为其着色,则必须相应地修改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 包( v2.0.0 ) 于 2021 年 10 月 19 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM