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

R语言中ggflags包已停止维护,geom_flag替代方案咨询

替代{ggflags}包geom_flag的方案

下面是几个可以实现用国家国旗替换绘图点的可行方案:

1. 使用{ggimage}包(推荐)

{ggimage}是ggplot2的扩展包,支持直接在绘图中插入图片,非常适合批量替换为国旗。你可以通过ISO 2字母国家代码拼接公开的国旗图片地址,直接调用geom_image实现:

# 安装加载包
install.packages("ggimage")
library(ggimage)
library(ggplot2)

# 示例数据
df <- data.frame(
  country = c("US", "CN", "GB", "JP"),
  value = c(100, 150, 90, 80)
)

# 绘制带国旗的图表
ggplot(df, aes(x = country, y = value)) +
  geom_image(
    aes(image = paste0("https://flagcdn.com/w20/", tolower(country), ".png")),
    size = 0.08  # 调整国旗大小
  ) +
  theme_minimal()

2. 使用{magick}+{ggplot2}自定义绘制

如果你需要更灵活地控制国旗样式(比如裁剪、调整颜色),可以用{magick}包读取国旗图片,再通过annotation_custom添加到ggplot中:

install.packages(c("magick", "ggplot2"))
library(magick)
library(ggplot2)
library(grid)

# 读取国旗图片
cn_flag <- image_read("https://flagcdn.com/w60/cn.png")

# 示例数据
df <- data.frame(x = "China", y = 150)

# 绘制图表
ggplot(df, aes(x, y)) +
  annotation_custom(
    rasterGrob(cn_flag),
    xmin = 0.8, xmax = 1.2,  # 控制国旗的横向范围
    ymin = 140, ymax = 160   # 控制国旗的纵向范围
  ) +
  theme_minimal()

这个方法适合单个或少量国旗的场景,批量处理时需要循环生成annotation。

3. 使用{ggflags}的GitHub维护分支

虽然官方{ggflags}包不再更新,但有开发者在GitHub维护了fork版本,可以直接安装使用,用法和原包完全一致:

# 先安装devtools
install.packages("devtools")
library(devtools)

# 安装GitHub上的维护版本
install_github("rensa/ggflags")
library(ggflags)
library(ggplot2)

# 示例数据(注意国家代码要小写)
df <- data.frame(
  country = c("us", "cn", "gb", "jp"),
  value = c(100, 150, 90, 80)
)

# 用geom_flag绘图
ggplot(df, aes(x = country, y = value)) +
  geom_flag(aes(country = country), size = 10) +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:55:58