定义"慢"。 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)
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() {
ddf$brk <- cut(ddf$value,
breaks=c(0, sort(ddf$value)),
labels=as.character(ddf[order(ddf$value),]$country),
include.lowest=TRUE)
wrld_simpl@data$id <- wrld_simpl@data$NAME
wrld <- fortify(wrld_simpl, region="id")
wrld <- subset(wrld, id != "Antarctica")
gg <- ggplot()
gg <- gg + geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat), fill="white", color="#7f7f7f", size=0.25)
gg <- gg + geom_map(data=ddf, map=wrld, aes(map_id=country, fill=brk), color="white", size=0.25)
gg <- gg + scale_fill_manual(values=colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value)),
name="Country")
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())
system.time(plotthem())
ggplot代码生成以下地图:
![enter image description here](https://istack.dev59.com/P101r.webp)
时间会因每次运行而异,但我从未见过它们相差超过一分钟(在我的系统上平均为0.6m,但我不打算进行详尽的基准测试)。
更新
随着您的需求逐渐被揭示,您可以很容易地用连续比例尺替换离散比例尺。
pal <- colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value))
palSz <- 10
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")
![图片描述](https://istack.dev59.com/HFOpN.webp)
听起来你应该坚持使用@Andy的rworldmap
,因为它抽象了复杂性。