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

如何使用geom_map在地图上绘制气温差异

嘿,你已经迈出了绘制全球气温图的关键一步!要通过geom_map清晰展示气温差异,核心是优化颜色映射和细节调整,咱们来一步步完善你的代码:

用geom_map可视化气温差异的实用技巧

1. 用颜色比例尺强化温度梯度(最关键)

气温差异的直观体现就是颜色渐变,你需要给fill=temperature搭配合适的比例尺。推荐两种常用方案:

连续色阶(适合展示精细温度变化)

用对色盲友好的viridis色系,比默认的渐变更美观且易读:

temperature_data %>% 
  filter(date >= as.Date("2010-03-01") & date <= as.Date("2010-03-31")) %>% 
  ggplot(aes(map_id = country)) +
  geom_map(aes(fill = temperature), map = map_data("world")) +
  expand_limits(x = map_data("world")$long, y = map_data("world")$lat) +
  # 新增viridis连续色阶,自定义图例标题和样式
  scale_fill_viridis_c(option = "plasma", name = "Temperature (°C)",
                       guide = guide_colorbar(title.position = "top", barwidth = 15)) +
  ggtitle("Worldwide Temperature Distribution - March 2010") +
  theme(plot.title = element_text(size = 15, face = "bold", color = "black"),
        legend.position = "bottom", # 把图例放在底部,不遮挡地图
        axis.title = element_text(size = 12)) +
  xlab("Longitude") + ylab("Latitude")

分箱色阶(适合区分温度区间)

如果想把气温分成明确的区间展示(比如“低温/中温/高温”),用分箱比例尺:

scale_fill_viridis_b(option = "mako", name = "Temperature (°C)",
                     bins = 5, # 分成5个区间
                     na.value = "lightgrey") # 给缺失数据的区域设为灰色

2. 可选:添加温度标注突出极端值

如果想让高/低温区域更醒目,可以给每个国家标注平均气温(先聚合数据再标注):

# 先计算每个国家3月的平均气温和中心经纬度
avg_temp_data <- temperature_data %>% 
  filter(date >= as.Date("2010-03-01") & date <= as.Date("2010-03-31")) %>% 
  group_by(country) %>% 
  summarise(avg_temp = mean(temperature, na.rm = TRUE),
            # 用世界地图数据的中心经纬度作为标注位置
            long = mean(map_data("world")$long[map_data("world")$region == country], na.rm = TRUE),
            lat = mean(map_data("world")$lat[map_data("world")$region == country], na.rm = TRUE))

# 绘制带标注的地图
ggplot() +
  geom_map(data = avg_temp_data, aes(map_id = country, fill = avg_temp), map = map_data("world")) +
  expand_limits(x = map_data("world")$long, y = map_data("world")$lat) +
  scale_fill_viridis_c(name = "Avg Temp (°C)") +
  # 添加温度标注,调整字号避免拥挤
  geom_text(data = avg_temp_data, aes(x = long, y = lat, label = round(avg_temp, 1)), size = 2.5) +
  ggtitle("Average March 2010 Temperatures with Labels") +
  theme_minimal()

3. 处理缺失数据

如果部分国家没有气温数据,用na.value给这些区域设置统一颜色(比如浅灰色),避免地图出现空白漏洞,让整体视觉更完整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:19:23