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

如何使用ggparty包为终端图添加百分比标签?

给ggparty节点柱形图添加百分比标签

要给每个柱形添加百分比标签,只需在geom_node_plot的绘图列表中加入geom_text,结合已有的panel_prop函数计算百分比并格式化显示,同时调整绘图布局避免标签截断。以下是修改后的完整代码:

library(ggparty)
library(scales) # 用于百分比格式化

data("WeatherPlay", package = "partykit")
wptree <- ctree(play ~ outlook, data=WeatherPlay, control = ctree_control(minsplit=1, minbucket=1, mincriterion = .01))

panel_prop <- function(count, panel) {
  count / tapply(count, panel, sum)[as.character(panel)]
}

ggparty(wptree) +
  geom_edge() +
  geom_edge_label() +
  geom_node_splitvar() +
  geom_node_plot(gglist = list(
    aes(
      y = play,
      x = after_stat(panel_prop(count, PANEL))
    ),
    geom_bar(stat = "identity"),
    geom_text(
      aes(
        label = percent(after_stat(panel_prop(count, PANEL)), accuracy = 1)
      ),
      hjust = -0.1,
      size = 3
    ),
    scale_x_continuous(labels = percent, expand = expansion(mult = c(0, 0.2))),
    theme(axis.text.x = element_text(angle = 0, vjust = 0.5))
  ))

关键修改说明:

  • 添加百分比标签:通过geom_text调用percent函数,将计算出的比例转为带%符号的文本,accuracy=1确保百分比保留整数。
  • 调整标签位置:hjust=-0.1让标签显示在柱形右侧,避免与柱形重叠。
  • 扩展x轴空间:scale_x_continuous的expand参数扩展x轴右侧范围,防止标签超出绘图区域;同时将x轴刻度也格式化为百分比,保持视觉统一。
  • 明确柱形统计方式:给geom_bar指定stat="identity",确保使用计算后的比例值绘制柱形。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:03:19