【问题标题】:Plot map with values for countries as color in R?在R中绘制带有国家值作为颜色的地图?
【发布时间】:2014-07-30 23:20:35
【问题描述】:

我有以下简单的示例数据,我想在地图上绘制与给定国家的值相对应的渐变颜色。

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)

特定国家可以按以下方式着色:Using [R] maps package - colouring in specific nations on a world map 使用命令:

plot(wrld_simpl, col = c(gray(.80), "red")[grepl("^U", wrld_simpl@data$NAME) + 1])

但是我怎样才能得到带有渐变颜色的上述数据的地图。 感谢您的帮助。

【问题讨论】:

  • 您要查找的术语是chorpleth
  • @TylerRinker 我认为你的意思是 choropleth

标签: r dictionary choropleth


【解决方案1】:

我认为其他答案有点复杂,也许是因为这个问题是在相对较长之前被问到/回答的?这是使用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())

【讨论】:

  • 感谢您的好回答。我问了这个问题 > 7 年前,当时不存在 ggplot2(我认为)。
  • @rnso 没问题,出于同样的原因,我刚刚更新了我的一个旧问题或答案。很高兴这些常见的问题可以随着环境的变化而更新:)
【解决方案2】:

定义“慢”。 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.6m,但我不打算进行广泛的基准测试)。

更新

随着您的需求不断被梳理出来,您可以相当轻松地将离散刻度替换为连续刻度。

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")

但是,听起来您可能应该坚持使用@Andy 的rworldmap,因为它抽象了复杂性。

【讨论】:

  • 谢谢。这很棒。我正在进一步尝试,并会给出回应。
  • 我们可以得到传说中的数字而不是国家名称吗?
  • 是的。只需更改ddf$brk 行中的labels
  • 将 $value 替换为 $country 有效,但如果两个值相同则失败。添加 'unique(' 可以纠正这个问题,但我希望显示调色板比例(如在 rworldmap 解决方案中)而不是值标签,这些标签通常不是 10、20 等圆形数字。
  • 我正在尝试自己做这件事,这在我上面的评论中应该很明显。感谢您的所有时间和精力。不是每个人都是程序员,我认为 R 不仅适用于程序员。我确信一段时间后 ggplot 会推出 geom_map() 函数,这将简化这一点。再次感谢。
【解决方案3】:

如果您想要更少的代码和更粗略的分辨率地图,您可以使用 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 paper

使用国家代码而不是名称会更快。

【讨论】:

  • 这真是太好了。最小,清晰的编码,快速执行,带有标题和图例数字比例的绘图。谢谢。
  • 对于印度行政级别(如州、城市)或可能是密码级别,是否可以在更精细的级别上提供类似的功能?
  • 我想知道为什么我得到 QuartzBitmap_Output - 无法打开文件 '/var/folders/5z/gtbz8c5x10lc6fc67n3flmq00000gn/T//Rtmpy5dZU6/7b05e095ecc1462eabffd93a610e7bfe.png
【解决方案4】:

可能没有优化:

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)

【讨论】:

  • 谢谢。我们可以得到一个图例来显示颜色对应的值吗?
  • @rnso 看看legend 函数。做一些腿部工作。
猜你喜欢
  • 2020-01-17
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 2021-11-07
  • 1970-01-01
  • 2019-01-09
相关资源
最近更新 更多