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_","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)
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
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
Good color choices make figures easier to read and interpret. In general:
#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:
Sequential palettes
Use for:
Diverging palettes
Use for:
Tips for choosing colors well
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:
I would use a qualitative palatte
What palette did you choose for numeric data?
I would use the Sequential palettes
In 3 to 5 sentences, explain why those choices make sense.
Qualitative palattes are used for categorical data because the colors that are used in each set differ from each other to allow for easier visualization of the categories. Sequential palettes are used to show numerical data because the colors are similar and on a graph it creates a gradient. The differences in the preset colors allows for them to be used to great advantage but only when used with the correct data.
Requirements
#qualitative data
data(mpg)
ggplot(mpg, aes(cty, fill = class)) +
geom_bar(position = "dodge") +
scale_fill_paletteer_d("ggthemes::Tableau_10")
ggplot(economics, aes(pop, psavert, color = date)) +
geom_point() +
scale_color_paletteer_c("viridis::magma")
Color choice matters in scientific graphs becasue it helps the reader easily see the difference in data. Color can also help show the relationships within data.
Create a bubble map in ggplot.
Requirements
Acceptable options
Suggested skills
install.packages("maps")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.5'
## (as 'lib' is unspecified)
library(maps)
##
## Attaching package: 'maps'
## The following object is masked from 'package:viridis':
##
## unemp
## The following object is masked from 'package:purrr':
##
## map
library(ggplot2)
library(dplyr)
cities <- data.frame(
city = c("New Delhi", "Beijing", "London", "Los Angeles", "Sydney", "Cairo"),
lat = c(28.6139, 39.9042, 51.5074, 34.0522, -33.8688, 30.0444),
lon = c(77.2090, 116.4074, -0.1278, -118.2437, 151.2093, 31.2357),
pm25 = c(110, 85, 25, 40, 15, 95), # air pollution levels
continent = c("Asia", "Asia", "Europe", "North America", "Australia", "Africa")
)
world_map <- map_data("world")
ggplot() +
geom_polygon(data = world_map,
aes(x = long, y = lat, group = group),
fill = "gray95", color = "gray70") +
geom_point(data = cities,
aes(x = lon, y = lat, size = pm25, color = continent),
alpha = 0.8) +
geom_text(data = cities,
aes(x = lon, y = lat, label = city)) +
scale_size(range = c(3, 14)) +
scale_color_brewer(palette = "Set2") +
coord_fixed(1.2) +
labs(
title = "Global Air Pollution Levels by City",
subtitle = "PM2.5 concentration comparison",
caption = "Bubble size represents PM2.5 levels (air pollution); color represents continent.",
x = "Longitude",
y = "Latitude",
size = "PM2.5 Level",
color = "Continent"
) +
theme_void()
Make one variation of your map using icon labels.
Requirements
Examples of what counts
highlight <- cities %>%
filter(city %in% c("New Delhi", "Beijing", "Cairo"))
ggplot() +
geom_polygon(data = world_map,
aes(x = long, y = lat, group = group),
fill = "gray95", color = "gray70") +
geom_point(data = cities,
aes(x = lon, y = lat, size = pm25, color = continent),
alpha = 0.8) +
geom_point(data = highlight,
aes(x = lon, y = lat),
shape = 8, size = 5, color = "black") +
geom_label(data = highlight,
aes(x = lon, y = lat, label = city),
nudge_y = 8,
size = 3,
fill = "white",
label.size = 0.3) +
scale_size(range = c(3, 14)) +
scale_color_brewer(palette = "Set2") +
coord_fixed(1.2) +
labs(
title = "Global Air Pollution Levels by City",
subtitle = "PM2.5 concentration comparison with highlighted cities",
caption = "Bubble size represents PM2.5 levels; color represents continent. Star icons highlight selected high-pollution cities.",
x = "Longitude",
y = "Latitude",
size = "PM2.5 Level",
color = "Continent"
) +
theme_void()
## Warning: The `label.size` argument of `geom_label()` is deprecated as of ggplot2 3.5.0.
## ℹ Please use the `linewidth` argument instead.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
When icons are added to a bubble graph and points the reader can easily identify the points being talked about. The icons can also show significance like in the graph above show where the polution levels are the highest.
You may invent a small dataset if needed. Keep it simple.
Example ideas
Build one Sankey diagram.
Requirements
Keep it basic: It does not need to be interactive or highly customized. The goal is to understand the structure.
library(networkD3)
library(dplyr)
links <- data.frame(
source=c("Field Hockey","Field Hockey", "Ice Hockey", "Lacrosse", "Lacrosse", "Baseball"),
target=c("Lacrosse","Dance", "Baseball", "Basketball", "Soccer", "Football"),
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
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
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(tidygraph)
##
## Attaching package: 'tidygraph'
## The following object is masked from 'package:igraph':
##
## groups
## The following object is masked from 'package:stats':
##
## filter
flareGraph <- tbl_graph(flare$vertices, flare$edges) %>%
mutate(
class = map_bfs_chr(node_is_root(), .f = function(node, dist, path, ...) {
if (dist <= 1) {
return(shortName[node])
}
path$result[[nrow(path)]]
})
)
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `class = map_bfs_chr(...)`.
## Caused by warning:
## ! The `father` argument of `bfs()` is deprecated as of igraph 2.2.0.
## ℹ Please use the `parent` argument instead.
## ℹ The deprecated feature was likely used in the tidygraph package.
## Please report the issue at <https://github.com/thomasp85/tidygraph/issues>.
importFrom <- match(flare$imports$from, flare$vertices$name)
importTo <- match(flare$imports$to, flare$vertices$name)
ggraph(flareGraph, 'dendrogram', circular = TRUE) +
geom_conn_bundle(aes(colour = after_stat(index)),
data = get_con(importFrom, importTo),
edge_alpha = 0.25
) +
geom_node_point(aes(filter = leaf, colour = class)) +
scale_edge_colour_distiller('', direction = 1, guide = 'edge_direction') +
coord_fixed() +
ggforce::theme_no_axes()
The edges represent import or dependency relationships between classes and the hiearchy represents the classes, organized by package and subclass relationships. Edge bundling is useful because it helps reduce visual clutter by grouping similar connections along shared paths in the hierarchy like powerstrips.