1

我需要在 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))

数据集将如下所示:

在此处输入图像描述

在此处输入图像描述

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

谢谢!

4

1 回答 1

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)

在此处输入图像描述

于 2019-09-16T13:36:25.420 回答