rggplot2ggalluvial

Show tow times change map with same color legend with ggalluvial


I have a map with 3 classes. I evaluated size of classes in two times. I am using dplyr, ggplot and ggalluvial libraries to present changes from 'First' time to 'Second' time.

data.frame(
First  = c("A", "B", "C","A","A"),
Second = c("A", "B", "C","B","C"),
Size   = c(83,  61,  32,  28, 16)
) %>%
ggplot(
  aes(
    axis1 = First,
    axis2 = Second,
    y = Size ,
    fill = Second )) +
geom_alluvium(aes(fill = Second )) +
geom_stratum() +
geom_text(
  stat = "stratum", 
  size = 5,
  aes(label = after_stat(stratum)))  +
theme_void() +
theme(legend.position = "none") 

But I have this figure

Figure with color changed

Ggalluvial shows no change classes with same color and clases with changes with grey color.

I need to present both axis with same color legend.

How could I do that?


Solution

  • You are trying to map the fill color of the first axis according to the value of Second, which doesn't make sense (there are three values for Second where First == A). You should map the stratum fill to after_stat(stratum), as you do for the geom_text labels:

    data.frame(
      First  = c("A", "B", "C","A","A"),
      Second = c("A", "B", "C","B","C"),
      Size   = c(83,  61,  32,  28, 16)
    ) %>%
      ggplot(
        aes(
          axis1 = First,
          axis2 = Second,
          y = Size)) +
      geom_alluvium(aes(fill = Second)) +
      geom_stratum(aes(fill = after_stat(stratum))) +
      geom_text(
        stat = "stratum", 
        size = 5,
        aes(label = after_stat(stratum)))  +
      theme_void() +
      theme(legend.position = "none") 
    

    enter image description here