如何在地图上的特定国家着色
How to color in a specific country on a map
我需要在仅中美洲的裁剪世界地图中为哥斯达黎加上色。
我已经编写的代码包含在下面...我希望能够使用 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)))
这是一种方法。我为哥斯达黎加创建了一个新数据 table,这样纬度和经度更容易获取,然后调用 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"))
一种更有效的方法是在
中包含 if()
或 ifelse()
语句
geom_sf(fill = ifelse(world$geounit == "Costa Rica", 'red', 'blue'))
我需要在仅中美洲的裁剪世界地图中为哥斯达黎加上色。
我已经编写的代码包含在下面...我希望能够使用 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)))
这是一种方法。我为哥斯达黎加创建了一个新数据 table,这样纬度和经度更容易获取,然后调用 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"))
一种更有效的方法是在
中包含if()
或 ifelse()
语句
geom_sf(fill = ifelse(world$geounit == "Costa Rica", 'red', 'blue'))