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

如何在sjPlot的plot_xtab堆叠视图中避免显示%0?

解决sjPlot绘制堆叠交叉表时出现%0的问题

方案1:启用remove.empty参数

直接在plot_xtab中添加remove.empty = TRUE,可自动移除占比为0的标签:

library(sjPlot)
library(palmerpenguins)

plot_xtab(penguins$island, penguins$species, bar.pos = "stack",
          margin = "row", show.n = FALSE, remove.empty = TRUE)

方案2:提前过滤无效数据

先筛选出存在观测值的岛屿-物种组合,再进行绘图:

library(sjPlot)
library(palmerpenguins)
library(dplyr)

# 过滤无观测记录的岛屿-物种组合
filtered_data <- penguins %>%
  group_by(island, species) %>%
  filter(n() > 0) %>%
  ungroup()

plot_xtab(filtered_data$island, filtered_data$species, bar.pos = "stack",
          margin = "row", show.n = FALSE)

方案3:自定义标签显示规则

如果不想完全移除0值条目,可自定义标签逻辑,让0值不显示百分比:

plot_xtab(penguins$island, penguins$species, bar.pos = "stack",
          margin = "row", show.n = FALSE,
          label = function(pct) ifelse(pct == 0, "", paste0(round(pct, 1), "%")))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:35:59