Search code examples
rggforce

In `ggforce/geom_parallel_sets_labels`, how to add more information to the bar label


In ggforce/geom_parallel_sets_labels , how to add the person count number to the black bar ? Thanks! (Below code use data Titanic, and want to show person count number in the bar )

library(tidyverse)
library(ggforce)

data <- reshape2::melt(Titanic)
data <- gather_set_data(data, 1:4)

ggplot(data, aes(x, id = id, split = y, value = value)) +
  geom_parallel_sets(aes(fill = Sex), alpha = 0.3, axis.width = 0.1) +
  geom_parallel_sets_axes(axis.width = 0.1) +
  geom_parallel_sets_labels(colour = 'white')

Solution

  • You could use after_stat to alter the default label and add e.g. the counts from the value column like so:

    library(tidyverse)
    library(ggforce)
    
    data <- reshape2::melt(Titanic)
    data <- gather_set_data(data, 1:4)
    
    ggplot(data, aes(x, id = id, split = y, value = value)) +
      geom_parallel_sets(aes(fill = Sex), axis.width = 0.3, alpha = 0.3) +
      geom_parallel_sets_axes(axis.width = 0.3) +
      geom_parallel_sets_labels(aes(label = after_stat(paste(label, value, sep = "\n"))), colour = 'white')
    

    UPDATE When using after_stat you only have access to the processed data, i.e. the data after it was processed by ggplot2 or ggforce, and only the variables which are contained in the this data, e.g. only variables which mapped on aesthetics are present in this data. Hence, the value_p column you added to the data is not available via after_stat. One option to fix that would be to add this column inside after_stat for which I use a custom helper function:

    helper_after_stat <- function(x, value, label) {
      data.frame(x = x, value = value, label = label) %>% 
        group_by(x) %>% 
        mutate(value_p = value / sum(value),
               label = paste(label, value, scales::percent(value_p), sep = "\n")) %>%
        pull(label)
    }
    
    ggplot(data, aes(x, id = id, split = y, value = value)) +
      geom_parallel_sets(aes(fill = Sex), axis.width = 0.3, alpha = 0.3) +
      geom_parallel_sets_axes(axis.width = 0.3) +
      geom_parallel_sets_labels(aes(label = after_stat(helper_after_stat(x, value, label))), colour = 'white')
    

    enter image description here