Reputation: 1192
I am trying to add the percent labels to each column on a plot. Below is a reproducible code that produces the plot but is missing the percentage labels for each column (shown as red labels in the image below). The code is from this post
library(ggparty)
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()
))
Upvotes: 1
Views: 60
Reputation: 125398
To achieve your desired result map on the label
aes too, where I additionally wrapped in scales::percent
to format as percentages, then add a geom_text
or geom_label
layer where we have to set stat="count"
. Finally I use coord_cartesian(clip = "off")
to avoid the labels from being clipped off.
library(ggparty)
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 / ave(count, PANEL, FUN = sum)
}
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)),
label = after_stat(scales::percent(panel_prop(count, PANEL))),
),
geom_bar(),
geom_label(stat = "count", hjust = 0),
coord_cartesian(clip = "off")
))
Upvotes: 2