How to make googleVis multiple sankey from data.frame?

purpose

I am going to do some Sankey in R using the package googleVis. The result should look something like this:

enter image description here

Data

I created some dummy data in R:

set.seed(1)

source <- sample(c("North","South","East","West"),100,replace=T)
mid <- sample(c("North ","South ","East ","West "),100,replace=T)
destination <- sample(c("North","South","East","West"),100,replace=T) # N.B. It is important to have a space after the second set of destinations to avoid a cycle
dummy <- rep(1,100) # For aggregation

dat <- data.frame(source,mid,destination,dummy)
aggdat <- aggregate(dummy~source+mid+destination,dat,sum)

What I tried so far

I can build Sankey with two variables if I have only the source and destination, but not the midpoint:

aggdat <- aggregate(dummy~source+destination,dat,sum)

library(googleVis)

p <- gvisSankey(aggdat,from="source",to="destination",weight="dummy")
plot(p)

The code produces the following:

enter image description here

Question

How do i change

p <- gvisSankey(aggdat,from="source",to="destination",weight="dummy")

to accept a variable mid?

+4
source share
1 answer

The function gvisSankeydoes accept mid-level levels. These levels must be encoded in the underlying data.

 source <- sample(c("NorthSrc", "SouthSrc", "EastSrc", "WestSrc"), 100, replace=T)
 mid <- sample(c("NorthMid", "SouthMid", "EastMid", "WestMid"), 100, replace=T)
 destination <- sample(c("NorthDes", "SouthDes", "EastDes", "WestDes"), 100, replace=T) 
 dummy <- rep(1,100) # For aggregation

Now we will change the source data:

 library(dplyr)

 datSM <- dat %>%
  group_by(source, mid) %>%
  summarise(toMid = sum(dummy) ) %>%
  ungroup()

datSM .

  datMD <- dat %>%
   group_by(mid, destination) %>%
   summarise(toDes = sum(dummy) ) %>%
   ungroup()

datMD Mid Destination. . ungroup colnames.

  colnames(datSM) <- colnames(datMD) <- c("From", "To", "Dummy")

datMD , gvisSankey .

  datVis <- rbind(datSM, datMD)

  p <- gvisSankey(datVis, from="From", to="To", weight="dummy")
  plot(p)

: Layered Sankey

+5

Source: https://habr.com/ru/post/1683025/


All Articles