12/8 積み上げグラフ

今日は積み上げグラフを描いてみます。メタゲノム解析で検出された細菌種を示すときとかに使われるのを見ますね。データはAirPassengersという既存のデータセットを使います。

このAirPassengersデータは時系列データセットというものらしく、初めて見たんですがぱっと見ベクトルっぽい感じでした。1949年1月から1960年12月までの飛行機の乗客数が並んでいます。

JanFebMarAprMayJunJulAug
1949112118132129121135148148136
1950115126141135125149170170158
1951145150178163172178199199184
1952171180193181183218230242209
196196236235229243264272237

というわけでまずこれをdataframeに変換したのち、3ヶ月ごとに一つの季節にまとめます。続いて処理を簡単にするため縦長データに変換します。

data.ap <- t(matrix(AirPassengers,ncol=12))
data.ap.season <- data.frame(year=seq(1949,1960),
                             winter=rowSums(data.ap[,c(1:2,12)]),
                             spring=rowSums(data.ap[,3:5]),
                             summer=rowSums(data.ap[,6:8]),
                             autumn=rowSums(data.ap[,9:11]))
data.ap.season.long <- pivot_longer(data.ap.season,
                                    colnames(data.ap.season)[-1],
                                    names_to = "season",
                                    values_to = "customers")

でこうなります

yearseasoncustomers
1949winter348
1949spring382
1949summer431
1949autumn359
1950winter381
1950spring401
1950summer489
1950autumn405
1951winter461
1951spring513
1951summer576

それでは各年の季節ごとの乗客数を積み上げ棒グラフにしてみましょう。

g <- ggplot(data.ap.season.long,aes(x=year,y=customers,fill=season))+
  theme_base()+
  geom_bar(stat = "identity")

積み上げ長を統一して割合を比較しやすくするには、geom_bar内のpositionを”fill”に指定します。

g <- ggplot(data.ap.season.long,aes(x=year,y=customers,fill=season))+
  theme_base()+
  geom_bar(stat = "identity",position = "fill")
ggsave("fig/1208_2.jpeg",g,width = 15,height = 12,units = "cm")

特に言いたいこともないので今日は終わりです。

コメントする