Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add custom label in the middle in Alluvial plot

I have below Alluvial plot

library(ggplot2)
library(ggalluvial)
data = structure(list(val = c(10, 30, 15, 30, 40, 12, 10, 30, 15), name = c("A", 
"B", "C", "A", "B", "C", "A", "B", "C"), group = c("gr1", "gr1", 
"gr1", "gr2", "gr2", "gr2", "gr3", "gr3", "gr3")), row.names = c(NA, 
-9L), class = "data.frame")
data['val1'] = c('45', '23', '44', '55', '34', '55', '12', '34', '89')
  ggplot(data,
       aes(x = group, stratum = name, alluvium = name,
           y = val,
           fill = name, label = val)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = name), alpha = .3, width = 1/9) +
  geom_stratum(aes(color = name), alpha = .9, width = 1/9) +
  geom_text(position = "stack", aes(x = group, y = val, label = val1))

As you can see, that the labels are not vertically aligned at centre of each block. Is there any way to achieve this?

Thanks for your pointer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you set position = "stack" in your geom_text() call, this is syntactic sugar for setting position = position_stack(vjust = 1, reverse = FALSE).

As you want your text vertically centered, you can explicitly call the position_stack() function, setting vjust = 0.5:

ggplot(data,
    aes(
        x = group, stratum = name, alluvium = name,
        y = val,
        fill = name, label = val
    )
) +
    scale_x_discrete(expand = c(.1, .1)) +
    geom_flow(aes(fill = name), alpha = .3, width = 1 / 9) +
    geom_stratum(aes(color = name), alpha = .9, width = 1 / 9) +
    geom_text(
        position = position_stack(), # only this line has changed
        aes(x = group, y = val, label = val1)
    )

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading