【R】ggsankey
2021年4月2日
1. はじめに
ggsankeyは、あるデータセットから他のデータセットへのフローを記述するsankey diagramを描いてくれるパッケージです。ノードとリンクも自動で生成してくれます。
2. インストール
CRANからインストールできます。
devtools::install_github("davidsjoberg/ggsankey")
3. 使ってみる
例に載っている簡単な例から。
library(tidyverse)
library(ggplot2)
library(ggsankey)
head(mtcars)
df <- mtcars %>%
make_long(cyl, vs, gear, carb)
ggplot(df, aes(x = x,
next_x = next_x,
node = node,
next_node = next_node,
fill = factor(node))) +
geom_sankey()

色を付けたり、ラベルを付けたり。
library(RColorBrewer)
ggplot(df, aes(x = x,
next_x = next_x,
node = node,
next_node = next_node,
fill = factor(node),
label = node)) +
geom_sankey(flow.alpha = .8,
node.color = "gray30") +
geom_sankey_label(size = 5, color = "white", fill = "gray10") +
scale_fill_brewer(palette = "Spectral") +
theme_sankey(base_size = 20) +
labs(x = NULL) +
theme(legend.position = "none",
plot.title = element_text(hjust = .5)) +
ggtitle("Specifications")

4. さいごに
最近、このようなフローを描画するプロットを多く見る気がします。