gpt4 book ai didi

r - 在 R 中绘制世界地图

转载 作者:行者123 更新时间:2023-12-03 21:19:26 27 4
gpt4 key购买 nike

我正在尝试使用 R 和 ggplot2 可视化来自世界地图中国家/地区的一些数据.我正在使用以下代码(示例):

WorldData <- map_data('world')
df <-data.frame(region=c('Hungary','Lithuania','Argentina'),value=c(4,10,11))
Total <- merge(WorldData,df,by='region')

并使用 ggplot 进行绘图:
p <- ggplot()
p <- p + geom_polygon(data=Total, aes(x=long, y=lat, group = group,fill=Total$value),colour="white") +
scale_fill_continuous(low = "thistle2", high = "darkred", guide="colorbar")
P1 <- p + theme_bw() + labs(fill = "legend" ,title = "Title", x="", y="")
P1 + scale_y_continuous(breaks=c()) + scale_x_continuous(breaks=c()) + theme(panel.border = element_blank())

输出是这样的:

enter image description here

我相信问题出在 merge因为当我更改 geom_polygon 中的数据选项时至 WorldDatafill 1 的选项我有以下结果:
enter image description here

发生这种情况是因为我没有来自 df 中所有国家/地区的数据吗? ?我怎样才能超越它?

编辑:我想要的是绘制整个 map 。 (我的描述不清楚)

最佳答案

您还可以在“图层”中工作,因为其他 GIS 环境允许您(这也将让您不合并数据)。这可以通过多种方式实现,但我喜欢使用 geom_map :

library(ggplot2)
library(dplyr)

WorldData <- map_data('world') %>% filter(region != "Antarctica") %>% fortify

df <- data.frame(region=c('Hungary','Lithuania','Argentina'),
value=c(4,10,11),
stringsAsFactors=FALSE)

p <- ggplot() +
geom_map(data = WorldData, map = WorldData,
aes(x = long, y = lat, group = group, map_id=region),
fill = "white", colour = "#7f7f7f", size=0.5) +
geom_map(data = df, map=WorldData,
aes(fill=value, map_id=region),
colour="#7f7f7f", size=0.5) +
coord_map("rectangular", lat0=0, xlim=c(-180,180), ylim=c(-60, 90)) +
scale_fill_continuous(low="thistle2", high="darkred", guide="colorbar") +
scale_y_continuous(breaks=c()) +
scale_x_continuous(breaks=c()) +
labs(fill="legend", title="Title", x="", y="") +
theme_bw()
p

enter image description here

这也有一个投影(通过 coord_map ),因此您将获得一致的输出并摆脱南极洲。

关于r - 在 R 中绘制世界地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30706124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com