Rで解析:データの分布をグラフで確認「ggridges」パッケージ

Rの解析に役に立つ記事

データの分布を確認するのに便利なパッケージの紹介です。気象庁から22.05.03の各都道府県の最高気温を0:00から23:00まで1時間毎に取得し、joyplotを作成するコマンドも紹介します。

パッケージバージョンは0.5.3。実行コマンドはwindows 11のR version 4.1.2で確認しています。

スポンサーリンク
スポンサーリンク

パッケージのインストール

下記コマンドを実行してください。

#パッケージのインストール
install.packages("ggridges")

コマンドの紹介

詳細はコマンド、パッケージのヘルプを確認してください。

#パッケージの読み込み:libraryコマンド
library("ggridges")

###データ例の作成#####
#tidyverseパッケージがなければインストール
if(!require("tidyverse", quietly = TRUE)){
  install.packages("tidyverse");require("tidyverse")
}
set.seed(1234)
n <- 500
TestData <- data.frame(Group = sample(paste0("Group", 1:5), n, replace = TRUE),
                          Time = sample(1:5, n, replace = TRUE),
                          height = rnorm(n),
                          Data2 = rnorm(n) + rnorm(n) + rnorm(n))
#geom_ridgeline用のデータ
TestRidgeLine <- TestData %>% group_by(Group, Time) %>%
  summarise_all(lst(mean)) %>% mutate(Yposi = recode(Group, Group1 = 0,
                                                     Group2 = .3, Group3 = .5,
                                                     Group4 = .7, Group5 = .9))
#######

#高さを指定したエリアプロットを作成:geom_ridgelineコマンド
#0以下の高さ表示する範囲を指定:min_heightオプション
ggplot(TestRidgeLine, aes(x = Time, y = Yposi,
                          height = height_mean, group = Yposi,
                          fill = Group)) +
  geom_ridgeline(show.legend = F, alpha = .5,
                 min_height = min(TestRidgeLine[, 3]))

#データ分布をプロット:geom_density_ridgesコマンド
#グラフ下部線付きプロット:geom_density_ridges2コマンド
ggplot(TestData, aes(x = height, y = Group, fill = Group)) +
  geom_density_ridges2(scale = 1) + facet_wrap(~Group)

#塗色を指定:scale_fill_cyclicalコマンド
#枠線を指定:scale_color_cyclicalコマンド
ggplot(TestData, aes(x = height, y = Group, fill = Group, color = Group)) +
  geom_density_ridges2(scale = 1, size = 1.5) + facet_wrap(~Group) +
  scale_fill_cyclical(values = c("blue", "green", "yellow")) +
  scale_color_cyclical(values = c("red", "black"))

出力例

・geom_ridgelineコマンド

・geom_density_ridgesコマンド

・scale_fill_cyclicalコマンド

気象庁から最高気温を取得

最高気温はNewMaxTempに格納しています。

#「tidyverse」パッケージを読み込み
if(!require("tidyverse", quietly = TRUE)){
  install.packages("tidyverse");require("tidyverse")
}
#都道府県を準備
JpanPref <- c("北海道", "青森県", "岩手県", "宮城県", "福島県", "茨城県", "千葉県",
              "秋田県", "山形県", "新潟県", "栃木県", "埼玉県", "東京都", "群馬県",
              "山梨県", "神奈川県", "富山県", "長野県", "静岡県", "石川県", "福井県",
              "岐阜県", "愛知県", "滋賀県", "三重県", "京都府", "奈良県", "和歌山県",
              "兵庫県", "大阪府", "鳥取県", "岡山県", "島根県", "広島県", "香川県",
              "徳島県", "愛媛県", "高知県", "山口県", "福岡県", "大分県", "宮崎県",
              "佐賀県", "熊本県", "鹿児島県", "長崎県", "沖縄県")

#時間文字列を作成
Hour <- paste0(formatC(0:23, width = 2, flag = "0"), "00")

#データ保管用変数
NewMaxTemp <- data.frame()

for(i in seq(Hour)){
  ###気象庁より20220503の毎時の最高気温を取得#####
  #参考:https://www.data.jma.go.jp/obd/stats/data/mdrr/docs/csv_dl_readme.html
  MaxTemp <- read.csv(paste0("https://www.data.jma.go.jp/obd/stats/data/mdrr/tem_rct/alltable/mxtemsadext00_20220503", Hour[i], ".csv"),
                         header = T, fileEncoding = "cp932")
  #最高気温処理
  GetMaxTemp <- NULL
  for(n in 1:47){
    #都道府県を抽出
    GetPrefData <- MaxTemp[which(MaxTemp[, 2] %in% grep(JpanPref[n], MaxTemp[, 2], value = TRUE)),]
    #最高気温を降順で並び替え
    GetPrefData <- GetPrefData[order(GetPrefData[, 10], decreasing = TRUE),]
    #最高気温を取得
    GetMaxTemp <- c(GetMaxTemp, GetPrefData[1, 10])
  }
  
  HourTemp <- cbind(Hour[i], JpanPref, GetMaxTemp)
  NewMaxTemp <- rbind(NewMaxTemp, HourTemp)
  
}

#列名を付与
colnames(NewMaxTemp) <- c("Hour", "Pref", "MaxTemp")

#最高気温を数値化
NewMaxTemp[, 3] <- type.convert(NewMaxTemp[, 3], as.is = TRUE)

#最高気温で都道府県を並び替え
#準備
NewMaxTemp %>%
  group_by(Pref) %>%
  summarise(Max = max(MaxTemp)) %>%
  arrange(Max) %>%
  mutate(Pref = factor(Pref)) %>%
  select(Pref) -> OrderVecPref
#並び替えとHourをfactor化
NewMaxTemp %>%
  mutate(Hour = factor(Hour),
         Pref = factor(Pref, levels = OrderVecPref$Pref)) -> NewMaxTemp

joyplotの作成

geom_density_ridgesコマンドを使う

#joyplotの作成:geom_density_ridgesコマンドを使う
ggplot(NewMaxTemp, aes(x = MaxTemp, y = Pref, fill = Pref)) +
  geom_density_ridges(show.legend = F) +
  geom_vline(xintercept = 26.6, col = "#ffc1c1") +
  theme(axis.text.y = element_text(size = 7.5),
        axis.text = element_text(colour = "#ffffe0"),
        panel.grid = element_blank(),
        panel.background = element_rect(fill = "#0a0a0a"),
        plot.background = element_rect(fill = "#0a0a0a"),
        plot.margin = unit(rep(0.2, 4), "cm"))

出力例


少しでも、あなたの解析が楽になりますように!!

タイトルとURLをコピーしました