【问题标题】:How to color in a specific country on a map如何在地图上的特定国家/地区着色
【发布时间】:2019-06-19 16:28:45
【问题描述】:

我需要在中美洲的裁剪世界地图中只为哥斯达黎加上色。

我已经编写的代码包含在下面...我希望能够使用 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)))

【问题讨论】:

    标签: r colors maps country


    【解决方案1】:

    这是一种方法。我为哥斯达黎加创建了一个新的数据表,以便更容易获得纬度和经度,然后称为 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"))
    

    【讨论】:

      【解决方案2】:

      更有效的方法是在以下语句中包含if()ifelse() 语句:

      geom_sf(fill = ifelse(world$geounit == "Costa Rica", 'red', 'blue'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多