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

解决ggplot2饼图中的空白切片问题

解决ggplot2 facet_wrap饼图出现空白切片的问题

问题原因

你遇到的空白切片是因为ing列作为因子,默认保留了所有初始类别(ing_A到ing_G),即使drop_na()后部分facet里没有对应的类别,ggplot依然会为这些不存在的类别预留位置,结合固定的scale_fill_manual颜色列表,就显示为空白切片。

解决方案

在数据预处理阶段,对每个type_n分组后,移除当前分组中未出现的ing因子水平即可。可以用forcats包的fct_drop()函数(tidyverse已包含)实现:

修改后的完整代码

# libraries
library(tidyverse) 
library(ggplot2) 

# dataset
B1_mf <- c(28, 5, NA, NA, 2, 58, 8)
B2_mf <-  c(27, NA, 8, NA, 2, 56, 8)
B3_mf <-  c(NA,NA,34,NA, 1, 59, 6)
B4_mf <-  c(NA,NA,NA,45, 1, 49, 5)
ing <- c("ing_A", "ing_B", "ing_C", "ing_D", "ing_E", "ing_F", "ing_G")
B_df <-  data.frame(ing, B1_mf, B2_mf, B3_mf, B4_mf)

# piechart
B_df %>%
    gather(key = "type_n", value = "mf", B1_mf, B2_mf, B3_mf, B4_mf) %>% 
    drop_na(mf) %>%
    # 关键步骤:按type_n分组,移除当前分组未出现的ing因子水平
    group_by(type_n) %>%
    mutate(ing = fct_drop(ing)) %>%
    ungroup() %>%
    ggplot(aes(x = 2,y = mf , fill = ing)) +
    geom_bar(stat = "identity", color = "black", size = 0.2) +  
    facet_wrap(~type_n, ncol = 4, scales = "fixed") +
    scale_fill_manual(values = c ("#c31e23", "#d85f52", "#e79184","#efc1b9", "#abbec8", "#658ea1", "#00607b")) +
    coord_polar(theta = "y", direction = -1) +
    geom_text(aes(label = mf), position = position_stack(vjust = 0.5), color = "white", size = 2) +
    theme_light() +
    theme(axis.text.y = element_blank(), 
        axis.text.x =element_blank(), 
        axis.title.x = element_blank(),
        axis.title.y = element_blank(), 
        axis.ticks.x=element_blank(),
        axis.ticks.y=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        legend.position="bottom", 
        legend.key.height = unit(0.4, 'cm'),
        legend.text = element_text(size =9), 
        legend.title = element_blank(),
        strip.background = element_blank(),
        strip.text = element_blank()) +
    xlim(1, 2.5)

补充说明

  • fct_drop(ing)会自动移除当前分组中没有出现的因子水平,确保每个facet只处理存在的类别,不会生成空白切片。
  • 不需要调整过滤阈值,保留所有需要的低数值数据(比如1、2这些值),同时解决空白问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:11:15