我們都知道常見的桑基圖只能表示A-B,B-C塔猾,但當(dāng)我們有多組數(shù)據(jù)需要進(jìn)行展示很明顯傳統(tǒng)的桑基圖已經(jīng)不能滿足我們的需求了稽坤,感謝瑞典科學(xué)家David Sjoberg開發(fā)了ggsanke包丈甸,下面通過幾個案例來展示如何繪制流動的桑基圖
Google 將sankey定義為:
sankey圖是一種可視化視圖尿褪,用于描述從一組值到另一組值的流程睦擂。被連接的事物稱為節(jié)點,而連接稱為鏈接杖玲。當(dāng)您要顯示一組數(shù)據(jù)的多個路徑之間的多對多映射時顿仇,最好使用Sankey
請看下圖方便對sankey進(jìn)行理解
ggsankey基本用法
devtools::install_github("davidsjoberg/ggsankey")
library(ggsankey)
library(tidyverse)
install.packages("gapminder")
library(gapminder)
colors <- c("#3B9AB2","#78B7C5","#EBCC2A","#E1AF00","#F21A00",
"#ECCBAE","#046C9A","#D69C4E","#ABDDDE","#000000")
df <- mtcars %>%
make_long(cyl, vs, am, gear, carb)
ggplot(df, aes(x = x,
next_x = next_x,
node = node,
next_node = next_node,
fill = factor(node))) +
geom_sankey()+
scale_fill_manual(values = colors)+
theme_minimal()+labs(x=NULL)
ggplot(df, aes(x = x, next_x = next_x,
node = node, next_node = next_node,
fill = factor(node), label = node)) +
geom_sankey(flow.alpha = .6,
node.color = "gray30") +
geom_sankey_label(size = 3, color = "white", fill = "gray40") +
scale_fill_manual(values = colors)+
theme_sankey(base_size = 18) +
labs(x = NULL) +
theme(legend.position = "none",
plot.title = element_text(hjust = .5)) +
ggtitle("Car features")
geom_alluvial;沖積圖非常類似于sankey圖摆马,但是節(jié)點之間沒有空格
ggplot(df, aes(x = x, next_x = next_x, node = node,
next_node = next_node,
fill = factor(node), label = node)) +
geom_alluvial(flow.alpha = .6) +
geom_alluvial_text(size = 4, color = "black") +
scale_fill_manual(values = colors)+
theme_alluvial(base_size = 18) +
labs(x = NULL) +
theme(legend.position = "none",
plot.title = element_text(hjust = .5)) +
ggtitle("Car features")
df <- gapminder %>%
group_by(continent, year) %>%
summarise(gdp = (sum(pop * gdpPercap)/1e9) %>%
round(0)) %>%
ungroup()
geom_sankey_bump臼闻;Sankey凹凸曲線圖是凹凸曲線圖和sankey的混合體,對于時間序列最有用囤采。當(dāng)一個組變得比另一個大時述呐,它會在其上方碰撞
ggplot(df, aes(x = year,
node = continent,
fill = continent,
value = gdp)) +
geom_sankey_bump(space = 0, type = "alluvial",
color = "transparent", smooth = 6) +
scale_fill_manual(values = colors)+
theme_sankey_bump(base_size = 16) +
labs(x = NULL,
y = "GDP ($ bn)",
fill = NULL,
color = NULL) +
theme(legend.position = "bottom") +
labs(title = "GDP development per continent")