user3357059
user3357059

Reputation: 1192

Add labels to terminal plots using the ggparty package

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()
  ))

Resulting enter image description here

Upvotes: 1

Views: 60

Answers (1)

stefan
stefan

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

Related Questions