r - 如何在 wrld_simpl 中为选定的国家/地区着色?

标签 r r-maptools

我有一个包含 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)

我想给一些国家上色,比如德国为红色,丹麦为绿色。我该怎么做?我尝试了类似的方法,但它没有按照我想要的方式工作:

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

谢谢!

最佳答案

尝试使用与 my_map$NAME 长度相同的向量而不是长度为 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)

关于r - 如何在 wrld_simpl 中为选定的国家/地区着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671710/

相关文章:

r - 无法隐藏列并在 Shiny DT 中设置行名 = FALSE

r - 在 R 中对数据框进行双重循环(使用 Levenshtein Dist 相互比较行)的最智能方法?

r - 如何在 R 中保存 Excel 文件并启用单元格保护?

r - 绘制制图错误 - 'This function does not give correct centroids and distances for longitude/latitude data.'

r - 为什么我在 R 中绘制的栅格图在保存的文件中会变得模糊?

r - 如何使用 maptools、ggplot 或其他软件包在 R map 中添加城市和质心的名称?

r - 有条件地用矩阵值替换 data.frame 列。 R 中的 VLOOKUP

string - 如何通过R中字符串的最后一个字符对数据帧进行子集化