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

如何在华夫饼图标记上显示国家旗帜?(以ggwaffle为例)

解决方案:用ggwaffle实现带国家旗帜的华夫饼图

方法1:使用支持旗帜的Emoji字体(推荐)

Windows系统需先安装支持国家旗帜的Emoji字体,比如Noto Color Emoji(可从Google Fonts下载安装)。安装完成后,修改代码如下:

library(ggplot2)
library(ggwaffle)

# 准备数据,将分组替换为对应旗帜emoji
iris2 <- iris
iris2$Species <- rep(c("🇺🇸", "🇨🇦", "🇬🇧"), each = nrow(iris)/3)

# 生成华夫饼图坐标数据
waffle_data <- waffle_iron(iris2, aes_d(group = Species))

ggplot(waffle_data, aes(x, y)) +
  # 用geom_text渲染旗帜emoji,指定支持的字体
  geom_text(aes(label = group), family = "Noto Color Emoji", size = 7) +
  coord_equal() +
  theme_waffle() +
  # 移除图例(若需要保留可删除该行)
  theme(legend.position = "none")

方法2:结合ggflags包实现

ggflags的geom_flag可在坐标点上绘制旗帜,完美适配ggwaffle生成的x/y坐标。步骤如下:

  1. 先安装ggflags包:
devtools::install_github("rensa/ggflags")
  1. 编写代码,用国家代码映射旗帜:
library(ggplot2)
library(ggwaffle)
library(ggflags)

# 准备数据,使用小写国家代码
iris2 <- iris
iris2$country <- rep(c("us", "ca", "gb"), each = nrow(iris)/3)

# 生成华夫饼图坐标数据
waffle_data <- waffle_iron(iris2, aes_d(group = country))

ggplot(waffle_data, aes(x, y)) +
  # 用geom_flag替换默认方块,绑定国家代码
  geom_flag(aes(country = group), size = 7) +
  coord_equal() +
  theme_waffle() +
  # 移除图例(若需要保留可删除该行)
  theme(legend.position = "none")

关键说明

  • 方法1依赖字体支持,安装Noto Color Emoji后,Windows系统可正常显示旗帜emoji,无需额外包。
  • 方法2通过ggflags直接绘制旗帜图片,不受系统字体限制,兼容性更强。
  • 若需要保留图例,可删除theme(legend.position = "none")语句,并按需调整图例样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:02:21