使用ggparty绘制决策树时移除子图Y轴文本的问题求助
移除ggparty决策树中指定子图的Y轴文本
要解决这个问题,仅调整geom_node_plot的scales和shared_axis_labels参数无法实现——因为gglist中的主题设置会全局应用到所有子图。正确的做法是使用node_plot_func自定义绘图逻辑,根据节点ID针对性隐藏Y轴文本。
完整解决方案代码
library(ggparty) library(tidyverse) library(partykit) ct <- ctree(Species ~ ., data = iris) panel_prop <- function(count, panel) { count / tapply(count, panel, sum)[as.character(panel)] } # 自定义节点绘图函数:根据节点ID控制Y轴文本显示 custom_plot <- function(node) { node_id <- node$node$id # 基础绘图框架 p <- ggplot(node$data, aes( y = Species, x = after_stat(panel_prop(count, PANEL)), fill = Species, label = after_stat(scales::percent(panel_prop(count, PANEL), accuracy = 1)) )) + geom_bar() + geom_text(stat = "count", hjust = 0, size = 3) + coord_cartesian(clip = "off") + scale_x_continuous(labels = scales::percent_format(accuracy = 1), expand = expansion(mult = c(.05, .25))) + theme(axis.text.x = element_text(size = 5)) + xlab("") + ylab("") # 仅保留根节点(id=1)的Y轴文本,其他节点隐藏 if (node_id != 1) { p <- p + theme(axis.text.y = element_blank()) } return(p) } ggparty(ct) + geom_edge() + geom_edge_label(colour = "gray9", size = 3) + geom_node_plot(scales = "fixed", shared_axis_labels = FALSE, node_plot_func = custom_plot) + geom_node_label(aes(), line_list = list(aes(label = paste("Node", id)), aes(label = splitvar), aes(label = "") ), line_gpar = list(list(size = 8, col = "black" ), list(size = 6), list(size = 8) ), ids = "inner")
关键说明
- 替换
gglist为node_plot_func:node_plot_func可以接收当前节点的完整信息,让我们能根据节点ID做个性化设置 - 节点ID判断逻辑:示例中仅保留根节点(id=1)的Y轴文本,若需要保留其他节点,只需修改判断条件(比如
node_id %in% c(1, 4)) - 主题局部修改:通过
theme(axis.text.y = element_blank())精准隐藏指定子图的Y轴文本,不影响其他绘图元素
内容的提问来源于stack exchange,提问作者user3357059
相关产品推荐
相关产品推荐

