我正在使用下面显示的 R 代码,它加载库 maps
和 RColorBrewer
,以创建一个世界地图,其中国家/地区按人口排名进行颜色编码。如下图所示,我使用的是绿色调色板,其中绿色越深,人口越多。
我想添加一个显示完整调色板的连续颜色图例,以表示浅绿色 = 人口少,深绿色 = 人口多,但我找不到通过 maps实现的方法
。您能告诉我向我的 map 添加连续颜色图例(或色键/色标)的最简单方法是什么吗?
# Load libraries
library(maps)
library(RColorBrewer)
# Load world data
data(world.cities)
# Calculate world population by country
world.pop = aggregate(x=world.cities$pop, by=list(world.cities$country.etc),
FUN=sum)
world.pop = setNames(world.pop, c('Country', 'Population'))
# Create a color palette
palette = colorRampPalette(brewer.pal(n=9, name='Greens'))(nrow(world.pop))
# Sort the colors in the same order as the countries' populations
palette = palette[rank(-world.pop$Population)]
# Draw a map of the world
map(database='world', fill=T, col=palette, bg='light blue')
最佳答案
maps
包中的世界地图大约有 30 年历史(例如,有苏联和南斯拉夫)。
此外,您的代码中存在一个小故障,导致格陵兰岛人口过剩,@Jealie 注意到了这一点(而印度的人口少于南极洲)。
您可以使用 rworldmap
创建一个与现代世界连续不断的传奇。
library(rworldmap)
library(RColorBrewer)
#get a coarse resolution map
sPDF <- getMap()
#using your green colours
mapDevice('x11') #create a map shaped device
numCats <- 100 #set number of categories to use
palette = colorRampPalette(brewer.pal(n=9, name='Greens'))(numCats)
mapCountryData(sPDF,
nameColumnToPlot="POP_EST",
catMethod="fixedWidth",
numCats=numCats,
colourPalette=palette)
您可以通过执行以下操作来更改图例,添加更多标签等:
mapParams <- mapCountryData(sPDF, nameColumnToPlot="POP_EST", catMethod="pretty", numCats=100, colourPalette=palette, addLegend=FALSE)
#add a modified legend using the same initial parameters as mapCountryData
do.call( addMapLegend, c( mapParams
, legendLabels="all"
, legendWidth=0.5
))
只是简单地探索一下代码中的故障。发生这种情况是因为您为 world.cities (239) 中的国家/地区数量创建了一个调色板,然后将其应用于 map 中世界数据库中的多边形数量 (2026)。所以它可能会被回收利用,你们国家的颜色与人口无关。下面的代码演示了问题的根源。
#find the countries used in the maps world map
mapCountries <- unique( map('world',namesonly=TRUE) )
length(mapCountries)
#[1] 2026
#exclude those containing ':' e.g. "USA:Alaska:Baranof Island"
mapCountries2 <- mapCountries[-grep(':',mapCountries)]
length(mapCountries2)
#[1] 186
#which don't match between the map and world.cities ?
#cityCountries <- unique( world.cities$country.etc )
cityCountries <- world.pop$Country
length(cityCountries)
#[1] 239
#which countries are in the map but not in world.cities ?
mapCountries2[ is.na(match(mapCountries2,cityCountries)) ]
#includes USSR, Yugoslavia & Czechoslovakia
关于r - 如何将连续的颜色图例添加到用 map 制作的 R map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443861/