*disclaimer
1197859
ggplot2
- ggplot2
- 基本:グラフの部品を重ねていく
- データの形式はlong-format
- 書き方のスタイル二種類
- geom_point
- geom_histogram
- geom_density() 確率密度推定
- データのカテゴリーによって表示を分けて塗りつぶす fill = 条件 オプション
- コントロール群と統制群の条件で分けてみる
- 事前・事後・遅延のタイミングで分けてみる
- 重なって見にくいので、透明度を設定:alpha=0.7
- 滑らかさの調整 adjust=2
- 二種類・二次元のデータの分布(散布図)
- どんなグラフを描くか指定する geom_
- 基本のスタイルを決める theme_
- 積み重ねの各段階を保存して、そこまでの出力をする
- 複数の種類のデータを重ねる
- 複数のグラフを配置する
- geom_line() 折れ線グラフを重ねる
- geom_bar()
- boxplot
- geom_text() 図の中に文字を入れる
- labs() 各種ラベル
- Tips
- ggplot2の独特な色づかい
- theme() で各種調整
- グラフの色を変える
- グラフの中に横線を挿入する
- グラフの中に注釈を入れる: annotate()
- 凡例のタイトルを表示しない
- 凡例を表示しない show.legend = FALSE
- 複数のグラフの配置 plot_grid()
- キャプションの追加
- グラフに数値を追加する: geom_text
- 凡例(legend)の見出しの文字の変更
- ラベルのいろいろ
- 書き方のスタイル二種類
- エラーバーをつける
- 折れ線の色を変える
- 折れ線のポイントに印をつけて、印を大きくする
- y軸の範囲を設定する
- y軸のラベルを設定する
- 軸のメモリを具体的に設定する(連続尺度)
- 軸のメモリを具体的に設定する(名義尺度)
- 軸を入れ替える: coord_flip()
- フォントサイズを設定する
- x軸、y軸のメモリのフォントを設定する。
- x軸、y軸の名称のフォントを設定する。
- グレー(白黒)のグラフにする
- グラフ全体の縦横比を決める
- 中でデータ処理: stat_関数
- 論文提出時のファイルについてのメモ
- 参考例
- References
基本:グラフの部品を重ねていく
- ggplot(データを指定)
- aes でグラフの要素の指定(横軸は何、縦軸は何) # aestheticより
- geom_何とかでグラフを書く
- geom_point で散布図
- geom_smooth で回帰線
- theme で見た目の設定(なくてもよい)
最低限これだけ
- 一種類のデータの分布
ggplot(data, aes(x = カラム名)) + geom_histogram()
- x軸とy軸に注意:boxplotはy軸しかないので
ggplot(data, aes(y = カラム名)) + geom_boxplot()
タイトルとx軸とy軸のラベル
ggtitle("タイトルを書きます") +
xlab("x軸のラベル") +
ylab("y軸のラベル") +
データの形式はlong-format
- tidyverseのパッケージのセットに入っているtidyrというパッケージの中のpivot_longer()を使って変換
サンプルデータ
> head(onomato.data2) subj cond timing score 1 1 exp pre 65 2 2 exp pre 75 3 3 exp pre 35 4 4 exp pre 70 5 5 exp pre 85 6 6 exp pre 55
- もしくは、gather()
書き方のスタイル二種類
g <- g + スタイル
g <- ggplot(SbyS.dat.long) g <- g + aes(x=value, fill=Year) g <- g + geom_density(alpha=.7) g <- g + facet_wrap(~name, scales="free") plot(g)
dplyrスタイル
SbyS.dat.long %>% ggplot(aes(x=value, fill=Year)) + geom_density(alpha=.7) + facet_wrap(~name, scales="free")
geom_point
ポイントの形の変更
g <- g + scale_shape_manual(values=c(1, 15))
| 数字 | 形 |
|---|---|
| 0 | □ |
| 1 | 〇 |
| 2 | △ |
| 5 | ◇ |
| 15 | ■ |
| 16 | ● |
| 17 | ▲ |
| 18 | ◆ |
ポイントの色の変更
g <- g + scale_color_manual(values=c("black", "darkgray"))
geom_histogram
> ggplot(onomato.data2, aes(x=score)) + geom_histogram()
geom_histogram(position = "dodge") 横に並べる
geom_density() 確率密度推定
> ggplot(onomato.data2, aes(x=score)) + geom_density()
データのカテゴリーによって表示を分けて塗りつぶす fill = 条件 オプション
> ggplot(onomato.data2, aes(x=score, fill = cond)) + geom_density()
コントロール群と統制群の条件で分けてみる
> ggplot(onomato.data2, aes(x=score, fill = timing)) + geom_density()
事前・事後・遅延のタイミングで分けてみる
重なって見にくいので、透明度を設定:alpha=0.7
ggplot(cn2cn3jpyTID, aes(x=SL, fill=year)) + geom_density(alpha=0.7)
滑らかさの調整 adjust=2
- デフォルトは1
二種類・二次元のデータの分布(散布図)
ggplot(data, aes(x, y)) + geom_point() + geom_smooth()
回帰直線にしたいときは
geom_smooth(method="lm")
- 細かい使い方は、
?geom_smooth
のようにして調べる。
> ggplot(shadow.tidy2, aes(x=Score, y=Ctest)) + geom_point() + geom_smooth() + theme_bw() >
どんなグラフを描くか指定する geom_
- geom_point() 散布図
- geom_smooth() 近似直(曲)線
- geom_smooth(method = "lm", とすると直線
- デフォルト(指定しないと)では、近似曲線
- データ1000以下は、loess()
- 1000以上はgam()
- geom_histogram() ヒストグラム
- geom_line() 折れ線グラフ
- geom_violin() バイオリンプロット
- geom_boxplot() 箱ひげ図
- geom_bar() 棒グラフ
- geom_density() カーネル密度推定で密度プロットを描写
基本のスタイルを決める theme_
スタイルのいろいろ
- theme_classic() クラシック:枠なし格子なし
- theme_bw() 白黒:黒枠灰色格子 ★わかりやすくてよい
- theme_minimal() 白黒:枠なし、灰色格子
- theme_grey() 灰色背景:いかにもggplot2
- theme_linedraw() はっきりした格子
- theme_light() 薄い格子
スタイルのオプション
- base_size=14 で、文字の大きさ設定(デフォルトは11)
- base_family=フォントの種類
積み重ねの各段階を保存して、そこまでの出力をする
- こうしておくと、各段階で、修正をしやすい。
step1 <- ggplot(data, aes()) step2 <- step1 + geom_point() step3 <- step2 + geom_smooth() step4 <- step3 + theme_classic() print(step4)
> step1 <- ggplot(shadow.tidy2, aes(x=Score, y=Ctest)) > step2 <- step1 + geom_point() > step3 <- step2 + geom_smooth(method="lm") > step4 <- step3 + theme_linedraw() > print(step4)
複数の種類のデータを重ねる
- クラスごととか
- 個人ごとに複数回のデータとか
- IDカラムに種類わけの番号を振っておく(tidydata形式)
- 一人が8週間エッセイを書いた例(pidで並べ替えて、weekで並べ替えた)
- データが整数になっていることを確認 なってない場合は、as.integer()
pid week score 8 1 1 1 4 1 2 1 3 1 3 2 6 1 4 3 7 1 5 3 2 1 6 3 5 1 7 3 1 1 8 3 9 2 1 2 12 2 2 3
ggplot(nicest.sample, aes(week, score, group = pid)) + geom_point() + geom_smooth(method = "lm", se = F)
- 一行目、group = pid に注意
- pidの番号でグループ化して、そのまとまりごとにグラフを描く
- 三行目、se = F に注意
- 信頼区間の表示をFALSEに
- 線が多すぎて、わかりにくいので、色を指定 aes()に color = 見出し オプションで指定。
ggplot(nicest.sample, aes(week, score, group = pid, color = pid)) +
geom_point() +
geom_smooth(method = "lm", se = F)
複数のグラフを別々に表示
facet_wrap(~pid) オプションの追加
- (~pid) に注意
- pid 毎に一枚ずつにするという意味
ggplot(nicest.sample, aes(week, score, group = pid)) + geom_point() + geom_smooth(method = "lm", se = F) + facet_wrap(~pid)
複数のグラフを配置する
library("gridExtra")
grid.arrange(一つ目の図, 二つ目の図, ncol=2)
facet
geom_line() 折れ線グラフを重ねる
- aes()で、color=IDで人ごとに色を変えるだけでなく、
- group=IDも合わせて指定することで、それぞれのIDのポイント間に線を引ける
g <- ggplot(sugi_iwa.dat) g <- g + aes(x=time, y=score, color=ID, group=ID) g <- g + geom_point() g <- g + geom_line() g <- g + facet_grid(~cond) plot(g)
geom_bar()
棒グラフを並べる
ggplot(final.long.data, aes(x=category, y=value, fill=students)) + geom_bar(stat="identity", position="dodge")
棒の輪郭を黒く縁取りする color="black"
棒の塗りつぶしのパタンを設定
g <- g + scale_fill_brewer(palette = "Greys")
棒の長さの比率の調整(重みづけ) weightをmappingする
- 事前に重みを決めておいて
alldata3.dat %>% mutate(weight = if_else(learning=="control", 0.5, 1))
- geom_bar()内でマッピングする
geom_bar(mapping = aes(weight = weight))
boxplot
geom_boxplot()
geom_text() 図の中に文字を入れる
geom_text(aes(label=name))
- 細かい指定は、geom_text_repel()で、
labs() 各種ラベル
labs(
title = "タイトル",
subtitle = "サブタイトル",
x = "X軸のラベル",
y = "Y軸のラベル",
caption = "説明文"
- グラフのタイトル
- x軸のラベル
- y軸のラベル
- 説明文
Tips
ggplot2の独特な色づかい
library(scales) show_col(hue_pal()(4))
theme() で各種調整
グラフの色を変える
- geom_boxplot()で、基本、独特な赤・緑・青になる
g <- g + aes(x=name, y=value, fill=name) g <- g + geom_boxplot()
- scale_fill_manual()で指定する
g <- g + aes(x=name, y=value, fill=name)
g <- g + geom_boxplot()
g <- g + scale_fill_manual(values = c("red", "blue", "green"))
plot(g)
- fill=name で色を付けているので scale_fill_manual()
- color=name で色を指定する場合は scale_color_manual()
グラフの中に横線を挿入する
g <- g + geom_hline(yintercept=2.05, color="red")
- geom_line()のオプションがつかえる
- linetype=
- 0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash
- linewidth=
- color=
- linetype=
グラフの中に注釈を入れる: annotate()
g <- g + geom_hline(yintercept=2.05, color="red")
g <- g + annotate("text", x= 15, y=2.1, label = "赤線は母語話者の平均MDD値")
- 最初の "text" で文字列を入れることを宣言
- ほかには、
- "rect" で長方形
- "segment" で線分
- ほかには、
- x, y は、描かれるグラフの中での座標
- 挿入される文字列の中心の座標(左寄せではない)
- https://ggplot2.tidyverse.org/reference/annotate.html
凡例のタイトルを表示しない
g <- g + theme(legend.title = element_blank())
凡例を表示しない show.legend = FALSE
geom_density(alpha=.7, show.legend = FALSE)
複数のグラフの配置 plot_grid()
- facetで並べるのではなくて、
- 個別にggplotで作成した複数のグラフをまとめて配置する。
install.packages("cowplot")
library(cowplot)
plot_grid(g.t, g.w, g.s, g.m, labels=c("Throw Class", "Whisper Class", "Send Class", "Mention Class"))
https://www.rdocumentation.org/packages/cowplot/versions/1.1.3/topics/plot_grid
キャプションの追加
labs(caption="ここに書く")
グラフに数値を追加する: geom_text
geom_text(aes(label=Freq, y=Freq +3), size=6)
- この場合頻度の棒グラフに、頻度の数字を表示
- y= で、数字を表示する位置を、頻度の棒グラフ上の横棒より3上の位置に表示する
- 表示するフォントの大きさを sizeで指定
- 位置をずらすには、, position = position_dodge(.9)
凡例(legend)の見出しの文字の変更
g <- g + scale_fill_discrete(name="入学年度")
ラベルのいろいろ
library(ggplot2)
SbyS.dat.long %>%
ggplot(aes(x=value, fill=Year)) +
geom_histogram() +
facet_wrap(~name, scales="free") +
labs(x = "スコア", y = "頻度", title="4スコアの比較", subtitle="学年別に", tag = "Fig. 1")
書き方のスタイル二種類
- g <- g + スタイル
g <- ggplot(SbyS.dat.long) g <- g + aes(x=value, fill=Year) g <- g + geom_density(alpha=.7) g <- g + facet_wrap(~name, scales="free") plot(g)
- dplyrスタイル
SbyS.dat.long %>% ggplot(aes(x=value, fill=Year)) + geom_density(alpha=.7) + facet_wrap(~name, scales="free")
エラーバーをつける
- 平均と標準誤差を事前に出しておく
- 標準誤差=標準偏差/sqrt(サンプルサイズ)
- 平均からプラスマイナス標準誤差を描く
geom_errorbar(aes(ymin = score.mean - score.se, ymax = score.mean + score.se, width = 0.3))
- widthは横の棒の長さ
折れ線の色を変える
g <- g + geom_line(aes(linetype = name))
単に geom_line(color="red") としてもよい。(細かいことはおまかせで)
折れ線のポイントに印をつけて、印を大きくする
g <- g + geom_point(aes(shape = name), size = 3)
単に geom_point(color = "red") としてもよい。(細かいことはお任せで)
y軸の範囲を設定する
ylim(c(1, 6))
+ scale_y_continuous(limits = c(0, 160))
y軸のラベルを設定する
ylab("Criterion Score")
軸のメモリを具体的に設定する(連続尺度)
g <- g + scale_x_continuous(breaks = seq(1,3,1)) g <- g + scale_y_continuous(breaks = seq(0,65, by = 5))
- x軸は1から始めて3まで、間隔は1
- y軸は0から始めて65まで、間隔は5
- 補助線をなくすには、 , minor_breaks = NULL をつける
scale_x_continuous(breaks=1:8, minor_breaks = NULL)
軸のメモリを具体的に設定する(名義尺度)
g <- g + scale_x_discrete(labels=c("Pre", "Post", "Delayed" ))
- 処理上は、1,2,3としておいて
- グラフの時に、事前、事後、遅延 と表記
軸を入れ替える: coord_flip()
フォントサイズを設定する
theme(text = element_text(size = 24))
http://array.cell-innovator.com/?p=3329
x軸、y軸のメモリのフォントを設定する。
theme(axis.text = element_text(size = 14))
- x軸だけの場合は、axis.text.x とする。
x軸、y軸の名称のフォントを設定する。
theme(axis.title = element_text(size = 14))
グレー(白黒)のグラフにする
g <- g + scale_fill_grey()
グラフ全体の縦横比を決める
g <- g + theme(aspect.ratio=2)
- 横1に対し縦2となる
中でデータ処理: stat_関数
https://qiita.com/swathci/items/b08496d863bca4b479b3
論文提出時のファイルについてのメモ
APAのテーマ:theme_apa
- jtoolsパッケージに含まれる
g <- g + theme_apa()
- 凡例の位置 legend.pos="位置" (位置は以下を組み合わせる)
- right
- left
- top
- middle
- bottom
- none (非表示)
https://rdrr.io/cran/jtools/man/theme_apa.html
タイトルのフォントの設定
- イタリックに
g <- g + theme(plot.title=element_text(face="italic"))
- サイズ
size=14
- フォントの種類
- 明朝体
family="serif"
- ゴシック体
sans-serif
カラーでも白黒でもわかりやすいグラフにする
- データポイントの形を変える
- geom_point(aes(shape=...))
- 線の形式を変える
- geom_line(aes(linestyle=...))
二つを比較する際にずらして見やすくする
, position = position_dodge(.2)
グラフだけ別ファイルで保存
- ggsave("ファイル名")
- データ形式は、拡張子で判定
- 解像度は、デフォルトで、300dpi
- png()で画像ファイルとして保存
- 処理が終わったら dev.off()すること
library(jtools)
library(ggplot2)
png("sample.png", width=2400, height=1600, res=300)
g <- ggplot(sample.dat)
g <- g + aes(x=Year, y=value, fill=Year)
g <- g + geom_boxplot()
g <- g + facet_wrap(~name, scales="free", ncol=4)
g <- g + ylab("Score")
g <- g + theme_apa(remove.y.gridlines = F, legend.pos="none")
plot(g)
dev.off()
参考例
散布図と回帰直線
- https://qiita.com/fujino-fpu/items/43b6bef969afae8b2375
- https://brain-storm.space/rggplot_scatterplot/751/
https://sugiura-ken.org/wiki/