我正在做一個專案,其中一小部分是用我的串列中的 135 個國家繪制世界地圖。我還有一個串列,說明它們是否已開發。
我如何將它放在世界地圖中以不同顏色顯示開發狀態?
我的資料看起來像這樣
Country Code Developed
Brazil BRA 1
Singapore SIN 3
France FRA 1
Poland POL 2
我從另一個問題中拍攝了下面的圖片,但理想情況下,它看起來像這樣,但有更多的國家和 3 種不同的顏色。
謝謝

uj5u.com熱心網友回復:
首先你需要安裝軟體包:
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
uj5u.com熱心網友回復:
如果要使用自己的資料為其著色,則必須相應地修改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 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/325055.html
下一篇:在ggplot中添加兩個圖例
