[英]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.