
R | ggplot | theme_minimal | 枠線なしの白に灰色の線がある背景にしたい
*ハイライト*
・theme_minimal()で枠線なしの白に灰色の線がある背景にできる
・背景にはさまざまが種類がある
install.packages("tidyverse")
library(ggplot2)
df <- data.frame(
subject = c("x1", "x2", "x3", "x4", "x5", "x6"),
weight = c(45, 53, 56, 72, 65, 50))
head(df, 2)
g <- ggplot(df, aes(x = subject, y = weight))+
geom_bar(stat = "identity")+
theme_minimal()
plot(g)

コードの説明
#パッケージのインストール
最初にパッケージをRにインストールしましょう。gglpot2はtidyverseというパッケージに内包されているので,tidyverseをインストールし,ggplot2をライブラリーします。
install.packages("tidyverse")
library(ggplot2)
#データフレームの作成
ggplotで棒グラフを作成するために被験者6人の体重を表しているデータフレームを作成します。subjectは「被験者」を,weightは「体重」を表しています。
df <- data.frame(
subject = c("x1", "x2", "x3", "x4", "x5", "x6"),
weight = c(45, 53, 56, 72, 65, 50))
head(df, 2)
subject weight
1 x1 45
2 x2 53
: : :
#棒グラフの描画
ggplotで被験者をX軸に,体重をY軸にマッピングし,体重の値に従って棒グラフを作成します。まずggplotのなかに使用するデータフレーム,データセットの中の変数をX軸やY軸に割り当てます。今回は体重の値をそのまま表示させたいので,geom_bar()の中身をstat = "idenetity"にしました。また棒グラフのバーに色をつけるために最初に指定したggplotのエステティックの部分にバーの塗りつぶしにfillを設定します。今回は被験者ごとに色分けをしたいので,fill = subjectとします。
g <- ggplot(df, aes(x = subject, y = weight))+
geom_bar(stat = "identity")
plot(g)

#背景の変更
枠線なしの白に灰色の線がある背景にするためにtheme_minimal()を書き加えます。
g <- ggplot(df, aes(x = subject, y = weight))+
geom_bar(stat = "identity")+
theme_minimal()
plot(g)

■Rグラフィックスクックブック 第2版 ―ggplot2によるグラフ作成のレシピ集/Winston Chang (著), 石井 弓美子 (翻訳), 河内 崇 (翻訳), 瀬戸山 雅人 (翻訳)
■改訂2版 RユーザのためのRStudio[実践]入門〜tidyverseによるモダンな分析フローの世界/松村 優哉 (著), 湯谷 啓明 (著), 紀ノ定 保礼 (著), 前田 和寛 (著)
■Rが生産性を高める〜データ分析ワークフロー効率化の実践/igjit (著), atusy (著), hanaori (著)
