[英]How to plot a world map using R
首先你需要安装软件包:
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/
如果要使用自己的数据为其着色,则必须相应地修改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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.