【问题标题】:R map package · Color some countriesR地图包·颜色一些国家
【发布时间】:2020-01-17 01:33:45
【问题描述】:

我需要在 R 地图中绘制一些国家,这些国家是从数据集中提供的。国家必须根据排名值(1到5)着色,十六进制颜色值将自动分配。

代码很简单:

library(maps)
library(geosphere)
library(magrittr)

# Renombramos columnas
colnames(dataset) <- c("paisRmap","pax")

# Top 5 destinos
dataset <- dataset[order(-dataset$pax)[1:5],]
dataset$pax[1] <- 5
dataset$pax[2] <- 4
dataset$pax[3] <- 3
dataset$pax[4] <- 2
dataset$pax[5] <- 1

# Quito Groenlandia
x <- map("world", plot=FALSE)
lista  <- (as.matrix(x$names))
paises <- lista[-664]
paises <- paises[-961]
paises <- paises[-486]
paises <- paises[-1426] 

# Mapa definitivo
map("world", regions=paises, xlim=c(-25,46),ylim=c(34.5,71), bg="white", interior = FALSE, lty = 0, col="#e6e6e6", fill=TRUE, mar = c(0.1, 0.1, 0, 0.1))

数据集将如下所示:

主要问题是我不知道如何指定要在地图中绘制的每个国家/地区的颜色。

谢谢!

【问题讨论】:

    标签: r maps geo colorize


    【解决方案1】:

    解决问题的可能方法。

    library(maps)
    library(geosphere)
    library(magrittr)
    
    x <- map("world", plot=FALSE)
    paises <- (as.matrix(x$names))
    
    # Set of countries to be colored
    cntry <- c("Italy", "Portugal", "France", "Germany", "Spain")
    # Set of colors for the selected countries
    colset <- rainbow(length(cntry))
    # Positions of the selected countries in the 'paises' vector
    poss <- lapply(cntry, function(x) grep(x, paises))
    # Vector of colors to be passed to 'map'
    cols <- unlist(sapply(1:length(cntry), function(k) rep(colset[k], length(poss[[k]]))))
    
    # Plot all european countries in gray
    map("world", regions=paises, xlim=c(-25,46),ylim=c(34.5,71), bg="white", 
       interior = FALSE, lty = 0, col="#e6e6e6", fill=T, mar = c(0.1, 0.1, 0, 0.1))
    
    # Plot the selected countries with the defined colors
    map("world", regions=paises[unlist(poss)], exact=T, xlim=c(-25,46),ylim=c(34.5,71), 
       bg="white", interior = FALSE, lty = 0, col=cols, fill=T, 
       mar = c(0.1, 0.1, 0, 0.1), add=T)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 2015-01-27
      • 2020-08-11
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多