Seymoo
Seymoo

Reputation: 189

Sankey Diagrams

I have seen this post 1 and Sankey plot in R to make a SAnkey plot but it is to complicated to understand !

If appreciate someone could explain how to make a Sankey plot for a data frame like below;

data.frame(row.names = paste0("SP","",1:30),
           COL1 = rep(sample(LETTERS[1:3]),10),
           COL3 = rep(sample(LETTERS[1:3]),10),
           COL3 = rep(sample(LETTERS[1:3]),10)
           )

So I can visualize the values 3 bars representing columns with 3 segments representing 3 factors "A", "B" and "C".

Upvotes: 0

Views: 359

Answers (1)

s__
s__

Reputation: 9485

let's try:

# load some packages!
library(alluvial)
library(ggalluvial)
require(ggplot2)
library(reshape)

# put the seed, to have consistency in random sample
set.seed(1)
data <- data.frame(row.names = paste0("SP","",1:30),
           id = paste0("SP","",1:30),              # added the rowlabels as id
           COL1 = rep(sample(LETTERS[1:3]),10),
           COL2 = rep(sample(LETTERS[1:3]),10),    # rename a column
           COL3 =rep(sample(LETTERS[1:3]),10))


# put data in long format, for ggplot
mdata <- melt(data, id=c("id")) 


# here the sankey, if it's like you want it
ggplot(mdata,aes(x = variable, stratum = value, alluvium = id, fill = value, label = value))+
  geom_flow(stat = "alluvium", lode.guidance = "rightleft") +
  geom_stratum() + geom_text(stat = "stratum")+
  theme(legend.position = "none") +
  ggtitle("test")



Here the result.

enter image description here

Upvotes: 1

Related Questions