Home > Net >  Add title above axis geom_alluvium
Add title above axis geom_alluvium

Time:03-23

How to add a title above axis1 and axis2 in geom_alluvium?

enter image description here

Similar to

enter image description here

Current code:

library(ggplot2)
library(ggalluvial)



df = data.frame(
  before = factor(c(4,2,3,1,1,1,2,4,2,2,1,4,3), labels = c("a","b","c","d")),
  after  = factor(c(3,3,2,1,3,4,4,1,1,2,2,4,3), labels = c("a","b","c","d")),
  N      = c(4,1,1,2,1,2,1,1,1,1,1,1,1)
)

ggplot(df, aes(y = N, axis1 = before, axis2 = after))    
  geom_alluvium(aes(fill = before))  
  geom_stratum()  
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum)))

CodePudding user response:

You could add a plain old geom_label:

ggplot(df, aes(y = N, axis1 = before, axis2 = after))    
  geom_alluvium(aes(fill = before))  
  geom_stratum()  
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum)))  
  geom_label(inherit.aes = FALSE,
            data = data.frame(x = c(1, 2), y = c(19, 19), 
                              label = c('Before', 'After')),
            aes(label = label, x = x, y = y))

enter image description here

Or, if you want to make it look like the labels are 'above' the plot, you could do:

ggplot(df, aes(y = N, axis1 = before, axis2 = after))    
  geom_alluvium(aes(fill = before))  
  geom_stratum()  
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum)))  
  annotate('rect', xmin = -Inf, xmax = Inf, ymax = Inf, ymin = 18.5,
           fill = 'white')  
  geom_text(inherit.aes = FALSE,
            data = data.frame(x = c(1, 2), y = c(19, 19), 
                              label = c('Before', 'After')),
            aes(label = label, x = x, y = y))

enter image description here

Or, if that feels like cheating, you can use annotate:

ggplot(df, aes(y = N, axis1 = before, axis2 = after))    
  geom_alluvium(aes(fill = before))  
  geom_stratum()  
  geom_text(stat = "stratum", mapping = aes(label = after_stat(stratum)))  
  coord_cartesian(clip = 'off', ylim = c(0, 18))  
  annotate('text', y = c(20, 20), x = c(1, 2), label = c('Before', 'After'))  
  theme(plot.margin = margin(30, 10, 10, 10))

enter image description here

  • Related