how to make a sankey in r

Here is an example code for creating a simple Sankey diagram in R using ggplot2 and networkD3 libraries.

main.r
# load libraries
library(ggplot2)
library(networkD3)

# create data
data <- data.frame(
  from = c("A", "A", "B", "B", "C", "C"),
  to = c("B", "C", "D", "E", "F", "G"),
  value = c(10, 30, 25, 5, 15, 20)
)

# create nodes and links data frames
nodes <- data.frame(name = unique(c(data$from, data$to)))
links <- merge(data, nodes, by.x = "from", by.y = "name")[, c(3, 2, 4)]
names(links) <- c("source", "target", "value")

# create sankey plot with ggplot2 and networkD3
p <- ggplot(links, aes(weight = value, source = source, target = target)) +
  geom_link(aes(color = factor(source)), width = 8) +
  geom_node_label(aes(label = name), fill = "white", colour = "black", alpha = 0.7) +
  scale_color_brewer(type = "qual", palette = "Set1") +
  theme_minimal() +
  theme(legend.position = "none",
    plot.title = element_text(hjust = 0.5)) +
  guides(fill = FALSE, color = FALSE) +
  labs(title = "Simple Sankey Diagram", x = NULL, y = NULL)

sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
 Target = "target", Value = "value", NodeID = "name", Group = "name",
 fontSize = 12, fontFamily = "Helvetica", nodeWidth = 30, units = "MW",
 nodePadding = 50, sinksRight = FALSE, colourScale = "d3.scaleOrdinal(d3.schemeCategory20);")
1243 chars
32 lines

This script generates the following Sankey diagram:

Sankey diagram

gistlibby LogSnag