如何用R的geom_map绘制欧洲密度填色地图(德语数据集)
嘿,你完全不用手动去查各国经纬度!ggplot2的生态里有现成的工具能帮你轻松搞定这个欧洲地图填充的需求,而且完全兼容德语的国家名称。我来一步步给你拆解解决方案:
1. 安装并加载必要的包
首先我们需要几个核心包:ggplot2用于绘图,rnaturalearth获取精准的欧洲地图数据,countrycode帮我们在不同语言的国名之间转换:
install.packages(c("ggplot2", "rnaturalearth", "rnaturalearthdata", "countrycode")) library(ggplot2) library(rnaturalearth) library(countrycode)
2. 准备地图数据并匹配德语国名
rnaturalearth包可以直接获取欧洲所有国家的地理数据,我们只需要把内置的英文国名转换成德语,就能和你的数据集完美匹配:
# 获取欧洲国家的矢量地图数据(返回sf格式,更适合现代ggplot2绘图) europe_map <- ne_countries(continent = "europe", returnclass = "sf") # 将地图数据中的英文国名转换为德语 europe_map$country_de <- countrycode(europe_map$name, origin = "country.name", destination = "country.name.de")
注意:你的数据集里的"England"对应的是英国的一部分,而地图数据通常按整个国家(英国)划分,所以我们需要调整一下数据集里的名称,才能正确匹配:
df <- data.frame( countries = c("Deutschland", "England", "Frankreich","Spanien"), satif = c(84,56,78,89) ) # 把"England"替换为德语的英国国名 df$countries <- ifelse(df$countries == "England", "Vereinigtes Königreich", df$countries)
3. 合并你的数据集与地图数据
把满意度数据和地图数据通过德语国名关联起来:
map_data <- merge(europe_map, df, by.x = "country_de", by.y = "countries", all.x = TRUE)
4. 绘制颜色填充的欧洲地图
现在用geom_sf(sf格式数据的专用绘图函数,比geom_map更简洁高效)来绘制带颜色填充的地图:
ggplot() + # 绘制地图,用satif值填充颜色 geom_sf(data = map_data, aes(fill = satif), color = "white", linewidth = 0.3) + # 设置颜色渐变(用viridis色系,颜色友好且辨识度高) scale_fill_viridis_c( option = "plasma", na.value = "lightgray", # 没有数据的国家用浅灰色填充 name = "Zufriedenheit (%)" # 图例标题 ) + # 用极简主题,隐藏坐标轴(地图不需要坐标轴) theme_minimal() + labs( title = "Europäische Länder: Zufriedenheitsrate", subtitle = "Basierend auf deinem Datensatz" ) + theme( axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank() # 隐藏网格线,让地图更清晰 )
如果你坚持要用
geom_map怎么办? 如果你一定要用geom_map而不是geom_sf,可以用maps包的传统地图数据,步骤类似:
install.packages("maps") library(maps) # 获取欧洲国家的传统地图数据 europe_map_old <- map_data("world", region = c("Germany", "UK", "France", "Spain")) # 转换国名为德语 europe_map_old$country_de <- countrycode(europe_map_old$region, origin = "country.name", destination = "country.name.de") # 合并数据 map_data_old <- merge(europe_map_old, df, by.x = "country_de", by.y = "countries", all.x = TRUE) # 用geom_map绘图 ggplot() + geom_map( data = map_data_old, map = map_data_old, aes(map_id = country_de, fill = satif), color = "white", linewidth = 0.3 ) + # 自动适配地图范围 expand_limits(x = map_data_old$long, y = map_data_old$lat) + scale_fill_viridis_c(option = "plasma", na.value = "lightgray", name = "Zufriedenheit (%)") + theme_minimal() + labs(title = "Europäische Länder: Zufriedenheitsrate", subtitle = "Mit geom_map") + theme(axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank())
关键问题解答
- 是否需要手动查找经纬度? 完全不需要!
rnaturalearth和maps包都内置了全球/各洲的地理数据,直接调用就能获取所有国家的边界和经纬度信息。 - ggplot2兼容德语/欧洲数据集吗? 当然兼容!只要做好国名的匹配转换(
countrycode包帮你一键搞定),ggplot2对非英文文本的支持非常好,标题、图例、标签都可以用德语正常显示。
内容的提问来源于stack exchange,提问作者Leon
相关产品推荐
相关产品推荐

