r - 绘制带有连续颜色图例的彩色地图
问题描述
我想绘制一张世界地图,其中包含根据其价值观着色的国家。我在这里找到了绘制地图,其中国家的值作为 R 中的颜色?第二个答案对我来说可能是一个很好的解决方案。特别是,我想用连续的颜色图例重现第二个答案中的第二个情节(见下文),但我没有成功。在plotme
函数中我不知道在哪里添加以下代码:
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")
我尝试用上面的代码替换以下代码,但出现错误“提供给连续刻度的离散值”:
gg <- gg + scale_fill_manual(values=colorRampPalette(brewer.pal(9, 'Reds'))(length(ddf$value)),
name="Country")
谁能帮忙重现剧情?
解决方案
您添加它而不是之前的填充比例 ( scale_fill_manual
)。但除此之外,您还需要将语句替换fill=brk
为fill=value
. 然后它应该工作。总而言之,新功能将如下所示(主要复制链接的答案):
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() {
# 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=value), color="white", size=0.25)
# this sets the scale and, hence, the legend
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")
# 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
}
plotme()
推荐阅读
- c# - 鼠标悬停在 C# 上时,我无法获得图像的正确坐标
- nginx - 如何将我的域重定向到 localhost:3000 使用 ngnix
- vb.net - 声明“Public variableName As String(,)”中的 (,) 是什么意思?
- excel - 在 Excel 中有没有办法显示包含文本字符串的单元格的数据透视表计数?
- angular - 如何从 Angular 9 Web 应用服务访问 GCP Secret Manager
- python-2.7 - Google App Engine deferred.defer 任务未执行
- ios - 自动滚动不适用于 SwiftUI 中的配音
- matplotlib - 在 matplotlib 中抑制对数刻度的额外刻度
- javascript - 如何使用更改事件选择多张图片?
- javascript - 动态创建的输入元素的 html 数组在 PHP Serverside 中未正确解释