2

I have a plot with a part of wrld_simpl

library(maptools)
data(wrld_simpl)
cntr <- c('Denmark', 'Germany', 'Norway', 'Ireland', 'United Kingdom', 'France', 'Italy', 
         'Sweden', 'Finland', 'Spain', 'Portugal', 'Latvia', 'Estonia', 'Slovenia', 'Belgium',
         'Netherlands', 'Austria', 'Poland', 'Switzerland', 'Slovakia', 'Lithuania', 'Croatia', 
         'Czech Republic') 
my_map <- wrld_simpl[wrld_simpl$NAME %in% cntr,]
plot(my_map)

I want to color some countries, let say Germany to red and Denmark to green. How can I do it? I tried something like this but it doesn't work the way I wanted:

country_colors <- list(Germany='red', Denamark='green')
plot(my_map, col=unlist(country_colors[as.character(my_map$NAME)]))

Thanks!

gagolews
  • 12,836
  • 2
  • 50
  • 75
jjankowiak
  • 3,010
  • 6
  • 28
  • 45
  • 1
    Why don't you create a new factor variable, perhaps called cntrcolor, and use ifelse() to assign the color you want to whichever countries. Then, in the plot call use an argument like fill=cntrcolor or color = contrcolor. – lawyeR Dec 28 '14 at 10:59

1 Answers1

2

Try using a vector of the the same length as my_map$NAME instead of a vector of length 2:

country_colors <- setNames(rep("white", length(my_map$NAME)), my_map$NAME)
country_colors[c("Germany", "Denmark")] <- c("red", "green") 
plot(my_map, col = country_colors)
lukeA
  • 53,097
  • 5
  • 97
  • 100