You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R绘制新冠检测总量世界地图时出现斜线问题求助

解决ggplot绘制世界地图出现斜线的问题

问题背景

尝试使用ggplot2和maps包绘制世界地图,根据各国新冠检测总量(Total_tests)填充渐变颜色,但生成的地图布满斜线。原始代码如下:

install.packages("maps")
library(maps)
library(ggplot2)

map_data_subset <- subset(covid, select = c("Country", "Continent","Total_tests", "Total_Deaths", "Total_Deaths_Per_Million"))
country_tests_deaths <- na.omit(map_data_subset)
world_map <- map_data("world")
merged_data <- merge(world_map, country_tests_deaths, by.x = "region", by.y = "Country", all.x = TRUE)

# Plotting map
ggplot(data = merged_data, aes(x = long, y = lat, group = group, fill = Total_tests)) +
  geom_polygon(color = "white") +
  scale_fill_gradient(low = "skyblue", high = "navyblue", name = "Your Legend") +
  theme_minimal()

问题原因

merge()函数会打乱world_map的原始行顺序。world_map中每个国家的地理多边形由连续的经纬度点序列构成,merge后这些点的顺序被打乱,geom_polygon绘制时会错误连接不相邻的点,最终出现斜线。

解决方案

使用dplyr::left_join()替代merge(),它会保留左表(world_map)的原始行顺序,确保每个国家的地理点序列连续。若未安装dplyr,先安装该包。

修正后的代码:

install.packages(c("maps", "dplyr"))
library(maps)
library(ggplot2)
library(dplyr)

# 处理数据
map_data_subset <- subset(covid, select = c("Country", "Total_tests"))
country_tests_deaths <- na.omit(map_data_subset)
world_map <- map_data("world")

# 用left_join替代merge,保留原始地理数据顺序
merged_data <- left_join(world_map, country_tests_deaths, by = c("region" = "Country"))

# 绘制地图,添加na.value处理无数据国家
ggplot(data = merged_data, aes(x = long, y = lat, group = group, fill = Total_tests)) +
  geom_polygon(color = "white") +
  scale_fill_gradient(low = "skyblue", high = "navyblue", 
                      name = "Total Tests",
                      na.value = "lightgray") + # 无数据国家显示浅灰色
  theme_minimal() +
  labs(title = "Global COVID-19 Total Tests")

额外说明

  • 部分地区(如Hong Kong、Taiwan)在maps包的world_map中未作为独立region存在,可能无法正确匹配,若需要显示这些地区,可单独处理地理数据或使用更详细的地图数据集(如rnaturalearth包)。
  • 若坚持使用merge(),可在合并后按group重新排序:merged_data <- merged_data[order(merged_data$group), ],但left_join更简洁可靠。

内容的提问来源于stack exchange,提问作者FreddyL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:32:08