Sankey Diagrams

library(networkD3)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# Make a connection data frame
links <- data.frame(
  source=c("group_A","group_A", "group_B", "group_C", "group_C", "group_E"), 
  target=c("group_C","group_D", "group_E", "group_F", "group_G", "group_H"), 
  value=c(2,3, 2, 3, 1, 3)
)
 
# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodes <- data.frame(
  name=c(as.character(links$source), as.character(links$target)) %>% 
    unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe. So we need to reformat it.
links$IDsource <- match(links$source, nodes$name)-1 
links$IDtarget <- match(links$target, nodes$name)-1
 
 
# Make the Network. I call my colour scale with the colourScale argument
p <- sankeyNetwork(Links = links, Nodes = nodes, Source = "IDsource", Target = "IDtarget", 
              Value = "value", NodeID = "name")
p
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.1     ✔ readr     2.2.0
## ✔ ggplot2   4.0.2     ✔ stringr   1.6.0
## ✔ lubridate 1.9.5     ✔ tibble    3.3.1
## ✔ purrr     1.2.1     ✔ tidyr     1.3.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(viridis)
## Loading required package: viridisLite
library(patchwork)
library(circlize)
## ========================================
## circlize version 0.4.18
## CRAN page: https://cran.r-project.org/package=circlize
## Github page: https://github.com/jokergoo/circlize
## Documentation: https://jokergoo.github.io/circlize_book/book/
## 
## If you use it in published research, please cite:
## Gu, Z. circlize implements and enhances circular visualization
##   in R. Bioinformatics 2014.
## 
## This message can be suppressed by:
##   suppressPackageStartupMessages(library(circlize))
## ========================================
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/13_AdjacencyDirectedWeighted.csv", header=TRUE)
# Package
library(networkD3)

# I need a long format
data_long <- data %>%
  rownames_to_column %>%
  gather(key = 'key', value = 'value', -rowname) %>%
  filter(value > 0)
colnames(data_long) <- c("source", "target", "value")
data_long$target <- paste(data_long$target, " ", sep="")

# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodes <- data.frame(name=c(as.character(data_long$source), as.character(data_long$target)) %>% unique())

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
data_long$IDsource=match(data_long$source, nodes$name)-1
data_long$IDtarget=match(data_long$target, nodes$name)-1

# prepare colour scale
ColourScal ='d3.scaleOrdinal() .range(["#FDE725FF","#B4DE2CFF","#6DCD59FF","#35B779FF","#1F9E89FF","#26828EFF","#31688EFF","#3E4A89FF","#482878FF","#440154FF"])'

# Make the Network
sankeyNetwork(Links = data_long, Nodes = nodes,
                     Source = "IDsource", Target = "IDtarget",
                     Value = "value", NodeID = "name",
                     sinksRight=FALSE, colourScale=ColourScal, nodeWidth=40, fontSize=13, nodePadding=20)

Arc Diagrams

An arc diagram is a special kind of network graph. It is consituted by nodes that represent entities and by links that show relationships between entities. In arc diagrams, nodes are displayed along a single axis and links are represented with arcs.

Here is a 2D vs arc example.

library(tidyverse)
library(viridis)
library(patchwork)
library(igraph)
## 
## Attaching package: 'igraph'
## The following object is masked from 'package:circlize':
## 
##     degree
## The following objects are masked from 'package:lubridate':
## 
##     %--%, union
## The following objects are masked from 'package:purrr':
## 
##     compose, simplify
## The following object is masked from 'package:tidyr':
## 
##     crossing
## The following object is masked from 'package:tibble':
## 
##     as_data_frame
## The following objects are masked from 'package:dplyr':
## 
##     as_data_frame, groups, union
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## The following object is masked from 'package:base':
## 
##     union
library(ggraph)
library(colormap)

# A really simple edge list
links=data.frame(
    source=c("A", "A", "A", "A", "B"),
    target=c("B", "C", "D", "F","E")
    )

# Transform to a igraph object
mygraph <- graph_from_data_frame(links)

# Make the usual network diagram
p1 <-  ggraph(mygraph) +
  geom_edge_link(edge_colour="black", edge_alpha=0.3, edge_width=0.2) +
  geom_node_point( color="#69b3a2", size=5) +
  geom_node_text( aes(label=name), repel = TRUE, size=8, color="#69b3a2") +
  theme_void() +
  theme(
    legend.position="none",
    plot.margin=unit(rep(2,4), "cm")
  )
## Using "tree" as default layout
# Make a cord diagram
p2 <-  ggraph(mygraph, layout="linear") +
  geom_edge_arc(edge_colour="black", edge_alpha=0.3, edge_width=0.2) +
  geom_node_point( color="#69b3a2", size=5) +
  geom_node_text( aes(label=name), repel = FALSE, size=8, color="#69b3a2", nudge_y=-0.1) +
  theme_void() +
  theme(
    legend.position="none",
    plot.margin=unit(rep(2,4), "cm")
  )

p1 + p2

Let’s look at more complicated examples: https://www.data-to-viz.com/graph/arc.html

Hierarchial Edge Bundling

Here is an example showing the same dataset with and without the use of bundling. The use of straight line on the left results in a cluttered figure that makes impossible to read the connection. The use of bundling on the right makes a neat figure:

# Libraries
library(tidyverse)
library(viridis)
library(patchwork)
library(ggraph)
library(igraph)

# The flare dataset is provided in ggraph
edges <- flare$edges
vertices <- flare$vertices %>% arrange(name) %>% mutate(name=factor(name, name))
connections <- flare$imports

# Preparation to draw labels properly:
vertices$id=NA
myleaves=which(is.na( match(vertices$name, edges$from) ))
nleaves=length(myleaves)
vertices$id[ myleaves ] = seq(1:nleaves)
vertices$angle= 90 - 360 * vertices$id / nleaves
vertices$hjust<-ifelse( vertices$angle < -90, 1, 0)
vertices$angle<-ifelse(vertices$angle < -90, vertices$angle+180, vertices$angle)

# Build a network object from this dataset:
mygraph <- graph_from_data_frame(edges, vertices = vertices)

# The connection object must refer to the ids of the leaves:
from = match( connections$from, vertices$name)
to = match( connections$to, vertices$name)

# Basic dendrogram
p1=ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
    geom_edge_link(size=0.4, alpha=0.1) +
    geom_node_text(aes(x = x*1.01, y=y*1.01, filter = leaf, label=shortName, angle = angle, hjust=hjust), size=1.5, alpha=1) +
    coord_fixed() +
    theme_void() +
    theme(
      legend.position="none",
      plot.margin=unit(c(0,0,0,0),"cm"),
    ) +
    expand_limits(x = c(-1.2, 1.2), y = c(-1.2, 1.2))
## Warning in geom_edge_link(size = 0.4, alpha = 0.1): Ignoring unknown
## parameters: `edge_size`
p2=ggraph(mygraph, layout = 'dendrogram', circular = TRUE) +
    geom_conn_bundle(data = get_con(from = from, to = to), alpha = 0.1, colour="#69b3a2") +
    geom_node_text(aes(x = x*1.01, y=y*1.01, filter = leaf, label=shortName, angle = angle, hjust=hjust), size=1.5, alpha=1) +
    coord_fixed() +
    theme_void() +
    theme(
      legend.position="none",
      plot.margin=unit(c(0,0,0,0),"cm"),
    ) +
    expand_limits(x = c(-1.2, 1.2), y = c(-1.2, 1.2))

p1 + p2

Some more examples: https://www.data-to-viz.com/graph/edge_bundling.html

Paleteer and Color Selection

Why color choice matters

Good color choices make figures easier to read and interpret. In general:

  • use qualitative palettes for categories
  • use sequential palettes for low-to-high numeric values
  • use diverging palettes when values split around a meaningful midpoint

Install and load packages

#install.packages("paletteer")
#install.packages("ggplot2")

library(ggplot2)
library(paletteer)

head(palettes_d_names) #discrete palettes
## # A tibble: 6 × 5
##   package palette      length type       novelty
##   <chr>   <chr>         <int> <chr>      <lgl>  
## 1 amerika Dem_Ind_Rep3      3 divergent  FALSE  
## 2 amerika Dem_Ind_Rep5      5 divergent  FALSE  
## 3 amerika Dem_Ind_Rep7      7 divergent  FALSE  
## 4 amerika Democrat          3 sequential FALSE  
## 5 amerika Republican        3 sequential FALSE  
## 6 awtools a_palette         8 sequential TRUE
head(palettes_c_names) #continuous palettes
## # A tibble: 6 × 3
##   package  palette               type      
##   <chr>    <chr>                 <chr>     
## 1 ggthemes Blue-Green Sequential sequential
## 2 ggthemes Blue Light            sequential
## 3 ggthemes Orange Light          sequential
## 4 ggthemes Blue                  sequential
## 5 ggthemes Orange                sequential
## 6 ggthemes Green                 sequential
head(palettes_dynamic_names) # palettes that can generate a variable number of colors
##       package    palette length       type
## 1 cartography   blue.pal     20 sequential
## 2 cartography orange.pal     20 sequential
## 3 cartography    red.pal     20 sequential
## 4 cartography  brown.pal     20 sequential
## 5 cartography  green.pal     20 sequential
## 6 cartography purple.pal     20 sequential
df_cat <- data.frame(
  group = c("A", "B", "C", "D"),
  value = c(12, 18, 9, 15)
)

df_cont <- data.frame(
  x = 1:10,
  y = c(3, 5, 6, 8, 9, 11, 12, 15, 16, 18)
)

ggplot(df_cat, aes(x = group, y = value, fill = group)) +
  geom_col() +
  scale_fill_paletteer_d("RColorBrewer::Set2") + #discrete palette
  theme_minimal()

ggplot(mtcars, aes(x = wt, y = mpg, color = hp)) +
  geom_point(size = 3) +
  scale_color_paletteer_c("viridis::plasma") + #continuous palette
  theme_minimal()

df_div <- data.frame(
  x = letters[1:6],
  change = c(-3, -1, 0, 2, 4, 6)
)

#Use a diverging palette when the data have a meaningful center, such as zero, average change, or control value.

ggplot(df_div, aes(x = x, y = change, fill = change)) +
  geom_col() +
  scale_fill_paletteer_c("scico::vik") + #divergent palette
  theme_minimal()

Qualitative palettes

Use for:

  • species
  • treatment groups
  • tissue types
  • countries
  • categories with no order

Sequential palettes

Use for:

  • abundance
  • expression level
  • temperature
  • concentration
  • any low-to-high variable

Diverging palettes

Use for:

  • fold change around zero
  • difference from a control
  • positive vs negative effects

Tips for choosing colors well

  1. Do not use too many categories at once
  2. Make sure colors are easy to distinguish
  3. Avoid relying on red/green alone
  4. Use color to support the message, not distract from it
  5. Keep palette choices consistent across related figures
  6. Example of manual extraction from paletteer

Homework

Part 1. Color selection with paletteer

Before making your figures, choose one palette you think works well for categorical data and one that works well for ordered or numeric data.

Task 1

Use paletteer to explore palettes and answer the following:

  • What palette did you choose for categorical data?
  • What palette did you choose for numeric data?
  • In 3 to 5 sentences, explain why those choices make sense.

Requirements

  • Include the code you used to preview or extract palettes
  • Include 1 to 2 sentences on why color choice matters in scientific graphics

I chose the set1 palette from ColorBrewer because the colors are bright and very easy to tell apart. This makes it simple to compare different groups without confusion. For numeric data, I chose Blues because it uses one color that gradually gets darker, which clearly shows increasing values. This helps people quickly see patterns from low to high. Both palettes are simple and easy to read.

Color choice matters because it helps people understand data faster. Clear colors make graphs easier to read, while bad colors can make them confusing.

# install if needed
install.packages("paletteer")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.5'
## (as 'lib' is unspecified)
library(paletteer)

# categorical palette
paletteer_d("RColorBrewer::Set1")
## <colors>
## #E41A1CFF #377EB8FF #4DAF4AFF #984EA3FF #FF7F00FF #FFFF33FF #A65628FF #F781BFFF #999999FF
# numeric palette
paletteer_c("grDevices::Blues", 10)
## <colors>
## #273871FF #305292FF #316DB3FF #5087C1FF #709FCDFF #8FB7D9FF #ACCCE4FF #C8DFEEFF #E1F0F8FF #F4FAFEFF

Part 2. Bubble Maps

Create a bubble map in ggplot.

Requirements

  1. plot at least 5 locations
  2. use bubble size to represent a numeric value
  3. use color intentionally with a palette you selected
  4. include text labels for the locations
  5. include a title
  6. include a short caption or note explaining what size and color represent

Acceptable options

  • one map that includes both bubble size and labels
  • or two versions of the same map, one emphasizing color and one emphasizing labels

Suggested skills

  • geom_point()
  • geom_text() or geom_label()
  • coord_cartesian() if you want to zoom in
  • theme_void() or another clean theme
library(ggplot2)

# simple dataset (5 locations)
data <- data.frame(
  location = c("NYC", "LA", "Chicago", "Houston", "Miami"),
  lon = c(-74.0060, -118.2437, -87.6298, -95.3698, -80.1918),
  lat = c(40.7128, 34.0522, 41.8781, 29.7604, 25.7617),
  value = c(100, 80, 60, 70, 50)
)

# bubble map
ggplot(data, aes(x = lon, y = lat)) +
  geom_point(aes(size = value, color = value)) +
  geom_text(aes(label = location), vjust = -1) +
  scale_color_gradient(low = "orange", high = "darkblue") +
  labs(
    title = "Bubble Map of U.S. Cities",
    caption = "Bubble size and color represent the value for each city"
  ) +
  theme_void()

Part 3. Map variation with icon labels.

Make one variation of your map using icon labels.

Requirements

  1. include at least 3 labeled locations
  2. labels can be marker icons, point symbols, or custom styled labels
  3. keep it readable and not overcrowded
  4. write 2 to 4 sentences explaining how this labeling style changes the way the map feels or reads

Examples of what counts

  • a leaflet map with popup markers
  • a static map with special point shapes and labels
  • a map using marker icons or custom annotation
library(ggplot2)

# same dataset
data <- data.frame(
  location = c("NYC", "LA", "Chicago", "Houston", "Miami"),
  lon = c(-74.0060, -118.2437, -87.6298, -95.3698, -80.1918),
  lat = c(40.7128, 34.0522, 41.8781, 29.7604, 25.7617),
  value = c(100, 80, 60, 70, 50)
)

# map with icon-style labels (shapes)
ggplot(data, aes(x = lon, y = lat)) +
  geom_point(aes(size = value, shape = location), color = "pink") +
  geom_text(aes(label = location), vjust = -1) +
  labs(
    title = "Bubble Map with Icon Labels",
    caption = "Different shapes act as icon labels for each city"
  ) +
  theme_void()

Using icon style labels like different shapes makes the map feel more visual and engaging. It helps separate locations more clearly. But, too many different shapes could make the map feel cluttered if not used carefully.

Part 4. Basic Sankey Diagram

You may invent a small dataset if needed. Keep it simple.

Example ideas

  1. students moving from major to career path
  2. genes grouped into pathway categories
  3. citation flow from field to topic
  4. patients moving from diagnosis group to treatment group

Build one Sankey diagram.

Requirements

  • include at least 3 source categories
  • include at least 3 destination categories
  • show flow values
  • use color intentionally
  • include a short figure caption explaining what the flows mean

Keep it basic: It does not need to be interactive or highly customized. The goal is to understand the structure.

# install if needed
install.packages("networkD3")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.5'
## (as 'lib' is unspecified)
library(networkD3)

# nodes (categories)
nodes <- data.frame(
  name = c("Biology", "Psychology", "Business",
           "Healthcare", "Research", "Corporate")
)

# links (flows)
links <- data.frame(
  source = c(0, 0, 1, 1, 2, 2),
  target = c(3, 4, 3, 5, 5, 4),
  value  = c(10, 5, 8, 6, 7, 4)
)

# sankey diagram
sankeyNetwork(
  Links = links,
  Nodes = nodes,
  Source = "source",
  Target = "target",
  Value = "value",
  NodeID = "name",
  units = "students"
)

This sankey diagram shows how students move from different majors to career paths. The width of each flow represents the number of students choosing that path. This helps visualize how groups are distributed acrss outcomes.

Part 5. Hierarchial edge building graph

Create one hierarchical edge bundling graph. You may use an example dataset from a package, adapt class example code, or create a very small hierarchy yourself.

Build one edge bundling graph.

Requirements

  1. include a hierarchical structure
  2. include linked nodes
  3. use color intentionally
  4. include a short paragraph answering:
  • What does the hierarchy represent?
  • What do the edges represent?
  • Why might edge bundling be useful compared with drawing all lines directly?

Note:This is meant to be an introduction, not a perfect polished figure. It is okay to rely on a tutorial example and then make small changes.

library(ggraph)
library(igraph)
library(tidygraph)
## 
## Attaching package: 'tidygraph'
## The following object is masked from 'package:igraph':
## 
##     groups
## The following object is masked from 'package:stats':
## 
##     filter
# create a simple hierarchy
edges <- data.frame(
  from = c("School", "School", "School", 
           "Biology", "Biology", 
           "Psychology", "Psychology"),
  to   = c("Biology", "Psychology", "Business",
           "Research", "Healthcare",
           "Clinical", "Counseling")
)

# create connections (links between end nodes)
connections <- data.frame(
  from = c("Research", "Healthcare", "Clinical"),
  to   = c("Clinical", "Counseling", "Research")
)

# build graph
graph <- graph_from_data_frame(edges)

graph <- as_tbl_graph(graph)

# plot
ggraph(graph, layout = "dendrogram", circular = TRUE) +
  geom_edge_diagonal(color = "lightblue") +
  geom_node_text(aes(label = name), size = 3, repel = TRUE) +
  theme_void()

The hierarchy represents how different academic fields are oganized within a school, starting from a general level and branching into more specific areas. The edges represent connections between related fields, such as shared topics or career paths.This makes the graph easier to read and helps highlight patterns in relationships.