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

R语言华夫图问题:韩国区域显示99个图标而非预期100个

华夫图图标数量缺失问题修复

问题描述

使用waffle包的geom_pictogram绘制华夫图时,设置make_proportional = TRUE与n_rows = 10,预期每个国家显示100个图标(10行×10列),但韩国区域仅显示99个图标。原始代码如下:

数据定义

df <- structure(list(country = c("Australia", "Australia", "Australia", 
"South Korea", "South Korea", "South Korea"), parts = c("case_1", 
"case_2", "non_case", "case_1", "case_2", "non_case"), values = c(1, 
19, 80, 1, 29, 70)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

绘图代码

library(tidyverse)
library(waffle)
df %>% ggplot(aes(label = parts, values = values)) +
    geom_pictogram(n_rows = 10, aes(color = parts),
                   family = 'fontawesome-webfont',
                   flip = TRUE, 
                   size = 6, 
                  show.legend = FALSE, 
                  make_proportional = TRUE
                  ) +
    scale_label_pictogram(
        name = "Confirmed cases",
        values = c("male"),
    ) +
    coord_equal() +theme_minimal() +
facet_wrap(~country, nrow = 2, strip.position = "top") 

问题原因

make_proportional = TRUE时,waffle包会将原始数值按比例转换为图标数量,但由于浮点运算的精度误差,部分分组的数值总和在转换后会出现1个单位的偏差(比如韩国的1+29+70=100,转换后总和变为99)。

解决方案

方案1:自动修正数值总和(无需手动计算比例)

通过分组处理数据,确保每个国家的图标总数严格为100,再关闭make_proportional参数:

library(tidyverse)
library(waffle)

# 修正数据:按国家分组调整数值,确保每组总和为100
df_fixed <- df %>%
  group_by(country) %>%
  mutate(
    # 先按比例转换为整数
    values_scaled = round(values / sum(values) * 100),
    # 最后一项补全,确保总和为100
    values_scaled = if_else(row_number() == n(), 100 - sum(values_scaled[-n()]), values_scaled)
  ) %>%
  ungroup()

# 使用修正后的数据绘图
df_fixed %>% 
  ggplot(aes(label = parts, values = values_scaled)) +
  geom_pictogram(n_rows = 10, aes(color = parts),
                 family = 'fontawesome-webfont',
                 flip = TRUE, 
                 size = 6, 
                 show.legend = FALSE, 
                 make_proportional = FALSE
  ) +
  scale_label_pictogram(
    name = "Confirmed cases",
    values = c("male"),
  ) +
  coord_equal() +
  theme_minimal() +
  facet_wrap(~country, nrow = 2, strip.position = "top") 

方案2:更新waffle包至最新版本

该问题可能是旧版本waffle的bug,运行以下命令更新包后重试:

update.packages("waffle")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:50:39