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

如何在R语言绘制的地图中为特定国家(法国)着色?

给特定国家(法国)着色的R地图解决方案

修改思路

不再基于continent设置填充色,而是创建标记列区分目标国家(法国)与其他国家,再针对性设置填充颜色。

修改后的完整代码

library(rnaturalearth)
library(sf)
library(ggplot2)
library(dplyr) # 用于数据处理

# 获取世界地图数据
world <- ne_countries(scale = 50, returnclass = 'sf')

# 添加标记列:标记是否为法国
world <- world %>%
  mutate(highlight = ifelse(name_long == "France", "France", "Other"))

# 绘制地图,针对法国设置特殊颜色
ggplot(world) +
  geom_sf(aes(fill = highlight), color = 'black') +
  coord_sf(crs = st_crs(3035),
           xlim = c(2800000, 6200000), 
           ylim = c(1500000, 4000000)) +
  # 设置填充颜色:法国用自定义颜色,其他用灰色
  scale_fill_manual(values = c("France" = "#1f77b4", "Other" = "grey"), 
                    guide = 'none') +
  theme(panel.background = element_rect(fill = "white"), # 补充背景色,避免留白
        panel.grid.major = element_line(linewidth = 0.1, color = "lightgrey"))

关键说明

  • 标记目标国家:通过mutate和ifelse判断name_long列(国家全名),给法国单独标记,其他国家归为一类。
  • 自定义颜色:在scale_fill_manual里可以替换"#1f77b4"为任意你喜欢的颜色(比如红色"red"、深绿"darkgreen")。
  • 优化主题:补充panel.background的fill参数,让地图背景更协调,避免默认透明背景的突兀感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:51:01