Rで解析:ggplot2のプロットを簡単アニメーション「gganimate」パッケージ

Rの解析に役に立つ記事

ggplot2のプロットを簡単にgifアニメーション化するパッケージの紹介です。非常に簡単に利用できるだけでなく、初期表示のシンボルの大きさや指定した色から本来の色へ変化するなどのシンボルへの視覚効果を設定することが可能です。大変面白いパッケージです。

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

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

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

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

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

実行コマンド

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

#パッケージの読み込み
library("gganimate")

###データ例の作成#####
set.seed(1234)
n <- 300
TestData <- data.frame(Year = sample(paste0(2021:2022), n, replace = TRUE),
                       Group = sample(paste0("Group", 1:3), n, replace = TRUE),
                       Data1 = runif(n) + sample(1:10, n, replace = TRUE),
                       Data2 = runif(n) * runif(n))
########

#アニメーション化するggplotオブジェクトを作成:transition_statesコマンド
#アニメーションの長さを設定:transition_lengthオプション
#アニメーション間の長さを設定:state_lengthオプション
TestPlot_1 <- ggplot(TestData, aes(x = Data1, y = Data2,
                     size = Data1, color = Group)) +
  geom_point() +
  guides(size = "none") +
  transition_states(states = Year,
                    transition_length = 2,
                    state_length = 1)
#表示
TestPlot_1

#アニメーションのイージング設定:ease_aesコマンド
#イージングとモディファイアをつなげて設定します
#例:"quartic-in"
#イージング種類:quadratic,cubic,quartic,quintic,sine
#circular,exponential,elastic,back,bounce
#モディファイア種類:-in,-out,-in-out
TestPlot_2 <- TestPlot_1 +
  ease_aes(y = "bounce-out")
#表示
TestPlot_2

#タイトルを変化する:ggplot2::ggtitleコマンド
#「glue」パッケージの記述を使います
TestPlot_3 <- TestPlot_2 +
  ggtitle("現在の表示は {closest_state} 年です。",
          subtitle = "Frame {frame} of {nframes}")
#表示
TestPlot_3

#色々な効果を付与
#enter_:表示前効果,exit_:表示後効果
TestPlot_4 <- TestPlot_3 +
  #フェードイン効果を付与:enter_fadeコマンド
  enter_fade() + 
  #初期表示のシンボルの大きさ:enter_growコマンド
  enter_grow(size = 10) +
  #初期を基準からずらして表示:enter_driftコマンド
  enter_drift(x_mod = -1.3, y_mod = 1.2) +
  #指定した色から本来の色へ変化する:enter_recolorコマンド
  enter_recolor(color = "black", fill = "black") +
  #フェードアウト効果を付与:exit_fadeコマンド
  exit_fade() +
  #本来の色から指定した色へ変化する:exit_recoloコマンド
  exit_recolor(color = "red") +
  #指定した基準へずらして表示:exit_driftコマンド
  exit_drift(x_mod = 10) +
  #指定したシンボルの大きさへ変化:exit_shrinkコマンド
  exit_shrink(size = 10)

#表示
TestPlot_4

###おまけ:BoxPlot#####
ggplot(TestData, aes(x = Group, y = Data2,
                     fill = Group)) +
  geom_boxplot() +
  guides(size = "none") +
  transition_states(states = Year,
                    transition_length = 2,
                    state_length = 1)

出力例

・色々な効果を付与:実行コマンドのTestPlot_4で表示されます。

・おまけ:BoxPlot


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

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