Search code examples
rggplot2tree

Is it possible to change the color scale with ggparty::geom_node_plot()?


I would expect to be able to change the fill colors in this plot with scale_fill_manual() but it doesn't work:

library(ggparty)
#> Loading required package: ggplot2
#> Loading required package: partykit
#> Loading required package: grid
#> Loading required package: libcoin
#> Loading required package: mvtnorm
sp_o <- partysplit(1L, index = 1:3)
n1 <- partynode(id = 1L, split = sp_o, kids = lapply(2L:4L, partynode))
t2 <- party(n1,
            data = WeatherPlay,
            fitted = data.frame(
              "(fitted)" = fitted_node(n1, data = WeatherPlay),
              "(response)" = WeatherPlay$play,
              check.names = FALSE),
            terms = terms(play ~ ., data = WeatherPlay)
)
ggparty(t2) +
  geom_edge() +
  geom_edge_label() +
  geom_node_splitvar() +
  # pass list to gglist containing all ggplot components we want to plot for each
  # (default: terminal) node
  geom_node_plot(gglist = list(geom_bar(aes(x = "", fill = play),
                                        position = position_fill()),
                               xlab("play") +
                                 scale_fill_manual(values = c("lightblue", "blue"))))

Created on 2023-03-03 with reprex v2.0.2

This code is from the Node Plot section of the ggparty "Graphic Partying" vignette with the exception of the scale_fill_manual() line.


Solution

  • You should remove the "+" and replace by "," in your ggplot formula list :

    library(ggparty)
    #> Loading required package: ggplot2
    #> Loading required package: partykit
    #> Loading required package: grid
    #> Loading required package: libcoin
    #> Loading required package: mvtnorm
    sp_o <- partysplit(1L, index = 1:3)
    n1 <-
      partynode(id = 1L,
                split = sp_o,
                kids = lapply(2L:4L, partynode))
    t2 <- party(
      n1,
      data = WeatherPlay,
      fitted = data.frame(
        "(fitted)" = fitted_node(n1, data = WeatherPlay),
        "(response)" = WeatherPlay$play,
        check.names = FALSE
      ),
      terms = terms(play ~ ., data = WeatherPlay)
    )
    ggparty(t2) +
      geom_edge() +
      geom_edge_label() +
      geom_node_splitvar() +
      # pass list to gglist containing all ggplot components we want to plot for each
      # (default: terminal) node
      geom_node_plot(gglist = list(
        geom_bar(aes(x = "", fill = play),
                 position = position_fill()),
        xlab("play") ,
          scale_fill_manual(values = c("lightblue", "blue"))
      ))