I'm trying to make a Sankey diagram in R using the alluvial package ( https://cran.r-project.org/web/packages/ggalluvial/vignettes/ggalluvial.html ). So far, I can replicate many of the examples that I've found. However, I'm specifically trying to replicate something that I haven't seen code for using the alluvial package.
Basically the dataset represents people arriving at a station (could be anything), some going onto next station, and some going missing (thus being truncated). In the alluvial package I can't figure out how to do this. I've attached a snapshot of what it should look like (made in http://sankeymatic.com/ ).
Should be fairly basic I imagine. One additional thing from the image I have shown is that I would like for the missing individuals bar to be a different colour at each node.
Could someone show me the code and code structure I would need for this?
You could try with package PantaRhei
:
library(PantaRhei)
library(tibble)
library(grid)
# define node position
nodes <-
tribble(
~ID, ~label, ~x, ~y, ~label_pos,
"s1", "Station 1", "1", "0", "below",
"s2a", "Station 2: arrived", "2", "0.1", "above",
"s2m", "Station 2: missing", "2", "s1", "below",
"s3a", "Station 3: arrived", "3", "0.2", "above",
"s3m", "Station 3: missing", "3", "s2a", "below",
"s4a", "Station 4: arrived", "4", "0.3", "above",
"s4m", "Station 4: missing", "4", "s3a", "below",
"s5a", "Station 5: arrived", "5", "0.4", "above",
"s5m", "Station 5: missing", "5", "s4a", "below"
)
# define size of flows
flows <-
tribble(
~from, ~to, ~substance, ~quantity,
"s1", "s2a", "a", 80,
"s1", "s2m", "m", 20,
"s2a", "s3a", "a", 60,
"s2a", "s3m", "m", 20,
"s3a", "s4a", "a", 35,
"s3a", "s4m", "m", 25,
"s4a", "s5a", "a", 15,
"s4a", "s5m", "m", 20
)
# define flow colours
colors <- tribble(
~substance, ~color,
"a", "green",
"m", "red"
)
# node formating
ns <- list(type = "bar",
gp=gpar(fill = "lightblue", col = "white", lwd = 1),
mag_pos = "inside",
mag_fmt = "%.0f")
# final sankey image
sankey(nodes, flows, colors, node_style = ns)
Which gives you:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.