R map package · Color some countries

143 Views Asked by At

I need to draw some countries in R map, these countries are provided from a dataset. Countries must be colorized depending on ranking value (1 to 5), hexadecimal color value will be asigned automatically.

Code is quite easy:

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))

Dataset will look like this:

enter image description here

enter image description here

Main problem is that I don't know how to specify each country colour to draw in the map.

Thanks!

1

There are 1 best solutions below

0
Marco Sandri On BEST ANSWER

A possible way to solve your problem.

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)

enter image description here