[英]Plot map with values for countries as color in R?
我有以下簡單的示例數據,我想用與給定國家/地區的值對應的漸變顏色在地圖上繪制這些數據。
ddf = read.table(text="
country value
USA 10
UK 30
Sweden 50
Japan 70
China 90
Germany 100
France 80
Italy 60
Nepal 40
Nigeria 20
", header=T)
在谷歌搜索上,我找到了幾個網站。 但是,我正在尋找小而清晰的代碼,並且最好應該是快速的(我發現 ggplot 方法相對較慢)。 世界地圖的分辨率不需要很高。
我嘗試了以下代碼:
library(maptools)
data(wrld_simpl)
plot(wrld_simpl)
特定國家可以按照以下方式着色: 使用 [R] 地圖包 - 在世界地圖上的特定國家中着色使用命令:
plot(wrld_simpl, col = c(gray(.80), "red")[grepl("^U", wrld_simpl@data$NAME) + 1])
但是我怎樣才能得到帶有漸變顏色的上述數據的地圖。 謝謝你的幫助。
定義“慢”。 ggplot提供了一種最靈活的方式,可以在幾秒鍾的時間內在地圖上顯示數據。
library(RColorBrewer)
library(maptools)
library(ggplot2)
data(wrld_simpl)
ddf = read.table(text="
country value
'United States' 10
'United Kingdom' 30
'Sweden' 50
'Japan' 70
'China' 90
'Germany' 100
'France' 80
'Italy' 60
'Nepal' 40
'Nigeria' 20", header=TRUE)
# Pascal had a #spiffy solution that is generally faster
plotPascal <- function() {
pal <- colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value))
pal <- pal[with(ddf, findInterval(value, sort(unique(value))))]
col <- rep(grey(0.8), length(wrld_simpl@data$NAME))
col[match(ddf$country, wrld_simpl@data$NAME)] <- pal
plot(wrld_simpl, col = col)
}
plotme <- function() {
# align colors to countries
ddf$brk <- cut(ddf$value,
breaks=c(0, sort(ddf$value)),
labels=as.character(ddf[order(ddf$value),]$country),
include.lowest=TRUE)
# this lets us use the contry name vs 3-letter ISO
wrld_simpl@data$id <- wrld_simpl@data$NAME
wrld <- fortify(wrld_simpl, region="id")
wrld <- subset(wrld, id != "Antarctica") # we don't rly need Antarctica
gg <- ggplot()
# setup base map
gg <- gg + geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat), fill="white", color="#7f7f7f", size=0.25)
# add our colored regions
gg <- gg + geom_map(data=ddf, map=wrld, aes(map_id=country, fill=brk), color="white", size=0.25)
# this sets the scale and, hence, the legend
gg <- gg + scale_fill_manual(values=colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value)),
name="Country")
# this gives us proper coords. mercator proj is default
gg <- gg + coord_map()
gg <- gg + labs(x="", y="")
gg <- gg + theme(plot.background = element_rect(fill = "transparent", colour = NA),
panel.border = element_blank(),
panel.background = element_rect(fill = "transparent", colour = NA),
panel.grid = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.position = "right")
gg
}
system.time(plotme())
## user system elapsed
## 1.911 0.005 1.915
system.time(plotthem())
## user system elapsed
## 1.125 0.014 1.138
ggplot代碼生成以下映射:
每次運行的時間有所不同,但我沒有看到它們相隔超過一分鍾(我的系統平均接近0.6米,但我不打算進行大量的基准測試)。
UPDATE
隨着您的要求不斷被淘汰,您可以相當容易地用連續的刻度替換離散刻度。
pal <- colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value))
palSz <- 10 # not sure what you really want/need for this range
gg <- gg + scale_fill_gradient2(low = pal[1],
mid = pal[palSz/2],
high = pal[palSz],
midpoint = (max(ddf$value) + min(ddf$value)) / 2,
name="value")
但是,聽起來你可能應該堅持rworldmap
的rworldmap
因為它抽象了復雜性。
如果你想要更少的代碼和更粗糙的分辨率圖,你可以使用rworldmap。
library(rworldmap)
#create a map-shaped window
mapDevice('x11')
#join to a coarse resolution map
spdf <- joinCountryData2Map(ddf, joinCode="NAME", nameJoinColumn="country")
mapCountryData(spdf, nameColumnToPlot="value", catMethod="fixedWidth")
可以更改默認分類,顏色和圖例,請參閱此RJournal報告 。
國家代碼而不是名稱會更快。
可能沒有優化:
library(RColorBrewer)
library(maptools)
data(wrld_simpl)
ddf = read.table(text="
country value
'United States' 10
'United Kingdom' 30
'Sweden' 50
'Japan' 70
'China' 90
'Germany' 100
'France' 80
'Italy' 60
'Nepal' 40
'Nigeria' 20", header=TRUE)
Reds
是調色板的名稱。 有關其他可用的調色板,請參閱?brewer.pal
。
pal <- colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value))
pal <- pal[with(ddf, findInterval(value, sort(unique(value))))]
col <- rep(grey(0.8), length(wrld_simpl@data$NAME))
col[match(ddf$country, wrld_simpl@data$NAME)] <- pal
plot(wrld_simpl, col = col)
我認為其他答案有點復雜,也許是因為這是在相對很久以前被問到/回答的? 這是使用ggplot2
的簡單方法。 我不知道關於這是否“快速”的基准是什么。
library(ggplot2)
library(dplyr)
ddf = read.table(text="
country value
USA 10
UK 30
Sweden 50
Japan 70
China 90
Germany 100
France 80
Italy 60
Nepal 40
Nigeria 20
", header=T)
world <- map_data("world")
world %>%
merge(ddf, by.x = "region", by.y = "country", all.x = T) %>%
arrange(group, order) %>%
ggplot(aes(x = long, y = lat, group = group, fill = value)) + geom_polygon()
這使得使用所有常見的ggplot2
句柄進行修改變得容易。 例如,如果我們想快速優化一下:
library(viridis)
world %>%
merge(ddf, by.x = "region", by.y = "country", all.x = T) %>%
arrange(group, order) %>%
ggplot(aes(x = long, y = lat, group = group, fill = value)) +
geom_polygon(color = "white", size = 0.2) +
scale_fill_viridis("", na.value = "gray90") +
theme_minimal() +
theme(axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.