サンキー・ダイアグラム1

riverplot パッケージ

(参考)
Rでウェブ解析:川の流れのようにデータをプロット!
参議院の議席の流れをsankey-diagramで可視化する

1
2
3
4
5
6
7
8
#N1:The ID of the first node
#N2:The ID of the second node
#Value:The width of the edge between N1 and N2
edges <- data.frame(
N1=c("総議席","改選","改選","改選","改選","改選","改選","改選","改選","改選","総議席"),
N2=c("改選","無所属","諸派","社民","維新","共産","みんな","公明","民主","自民","非改選"),
Value=c(121,2,1,1,8,8,8,11,17,65,121),stringsAsFactors = F )
edges

N1 N2 Value
1 総議席 改選 121
2 改選 無所属 2
3 改選 諸派 1
4 改選 社民 1
5 改選 維新 8
6 改選 共産 8
7 改選 みんな 8
8 改選 公明 11
9 改選 民主 17
10 改選 自民 65
11 総議席 非改選 121

1
2
3
4
5
6
7
8
# containing at least the columns "ID" and "x" (horizontal
#position of the node)
#
# Optionally, it can also contain columns "labels" (the labels to display)
#and "y" (vertical position of the node on the plot)
nodes = data.frame(ID = unique(c(edges$N1, edges$N2)), stringsAsFactors = FALSE)
nodes$x = c(1,2,rep(3,10))
nodes

ID x
1 総議席 1
2 改選 2
3 無所属 3
4 諸派 3
5 社民 3
6 維新 3
7 共産 3
8 みんな 3
9 公明 3
10 民主 3
11 自民 3
12 非改選 3

1
2
3
4
5
6
library(riverplot)
rp <- list(nodes = nodes, edges = edges)
class(rp) <- c(class(rp), "riverplot")
#png("rp01.png",width=800,height=800)
plot(rp, plot_area = 0.95,gravity = "top")
#dev.off()

時計回りに90度回転した

ラベルを指定。色付け。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
edges <- data.frame(
N1=c("総議席","改選","改選","改選","改選","改選","改選","改選","改選","改選","総議席"),
N2=c("改選","無所属","諸派","社民","維新","共産","みんな","公明","民主","自民","非改選"),
Value=c(121,2,1,1,8,8,8,11,17,65,121),stringsAsFactors = F )
#
nodes = data.frame(ID = unique(c(edges$N1, edges$N2)), stringsAsFactors = FALSE)
nodes$x = c(1,2,rep(3,10))
#ラベルの位置を調整する(全角スペースで調整)ためにnodesのlabelsを指定
nodes$labels = c("    総議席","改選   ","無所属   ","諸派   ","社民   ","維新   ",
"共産   ","みんな   ","公明   ","民主   ","自民   ","非改選   ")
#nodes
library(RColorBrewer)
palette = brewer.pal(12, "Set3")
styles = lapply(1:12, function(n) {
list(col = palette[n])
})
names(styles) = nodes$ID
library(riverplot)
rp <- list(nodes = nodes, edges = edges,styles=styles)
class(rp) <- c(class(rp), "riverplot")
#srt=0で横書き
#png("rp02.png",width=1000,height=800)
plot(rp, plot_area = 0.95, srt=0,gravity = "top")
#dev.off()