如何在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
相关产品推荐
相关产品推荐

