如何在地图上填色特定国家

3

我需要在一个裁剪过的中美洲世界地图中只标注哥斯达黎加。

我已经编写的代码如下... 我想使用ggplot2和sf库来完成这个任务。

library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("maps")
world <- ne_countries(scale='medium',returnclass = 'sf')
class(world)


(CentralAmerica <- ggplot(data = world) +
  geom_sf()  +
  coord_sf(xlim = c(-60, -120), ylim = c(5, 35), expand = FALSE) +
  scale_fill_viridis_d(option = "plasma") +
  theme(panel.background = element_rect(fill = "azure"),
     panel.border = element_rect(fill = NA)))
2个回答

3
更有效的方法是在以下代码中包含if()ifelse()语句:
geom_sf(fill = ifelse(world$geounit == "Costa Rica", 'red', 'blue'))

0
这是一种方法。我创建了一个新的数据表格,使得获取哥斯达黎加的纬度和经度更加容易,然后调用了geom_polygon函数:
library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("maps")
library("data.table")
world <- ne_countries(scale='medium',returnclass = 'sf')
class(world)

CR_DT <- world[world$name == "Costa Rica",]
CR_DT2 <- as.data.table(CR_DT)[, unlist(geometry)]
CR_DT3 <- setNames(data.table(matrix(nrow = 133, ncol=2)), c("lng", "lat"))
CR_DT3$lng <- CR_DT2[1:133]
CR_DT3$lat <- CR_DT2[134:266]

(CentralAmerica <- ggplot(data = world) +
geom_sf()  +
coord_sf(xlim = c(-60, -120), ylim = c(5, 35), expand = FALSE) +
scale_fill_viridis_d(option = "plasma") +
theme(panel.background = element_rect(fill = "azure"),
      panel.border = element_rect(fill = NA)) +    
geom_polygon(data=CR_DT3, aes(x=lng, y=lat, fill="blue"), colour="red"))

Map of Costa Rica


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接