{{category R}} R.package !!!ggplot2 {{outline}} ---- !!基本:グラフの部品を重ねていく +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()を使って変換 !サンプルデータ {{pre > 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 + スタイル {{pre 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スタイル {{pre 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() {{ref_image histo1.png}} !geom_histogram(position = "dodge") 横に並べる !!geom_density() 確率密度推定 > ggplot(onomato.data2, aes(x=score)) + geom_density() {{ref_image density1.png}} !データのカテゴリーによって表示を分けて塗りつぶす fill = 条件 オプション > ggplot(onomato.data2, aes(x=score, fill = cond)) + geom_density() !コントロール群と統制群の条件で分けてみる {{ref_image cond1.png}} > ggplot(onomato.data2, aes(x=score, fill = timing)) + geom_density() !事前・事後・遅延のタイミングで分けてみる {{ref_image timing1.png}} !重なって見にくいので、透明度を設定:alpha=0.7 {{pre ggplot(cn2cn3jpyTID, aes(x=SL, fill=year)) + geom_density(alpha=0.7) }} {{ref_image SL.png}} !滑らかさの調整 adjust=2 *デフォルトは1 !!二種類・二次元のデータの分布(散布図) ggplot(data, aes(x, y)) + geom_point() + geom_smooth() !回帰直線にしたいときは geom_smooth(<>) *細かい使い方は、 ?geom_smooth のようにして調べる。 {{pre > ggplot(shadow.tidy2, aes(x=Score, y=Ctest)) + geom_point() + geom_smooth() + theme_bw() > }} {{ref_image Score-Ctest.png}} !!どんなグラフを描くか指定する 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=フォントの種類 !!積み重ねの各段階を保存して、そこまでの出力をする *こうしておくと、各段階で、修正をしやすい。 {{pre step1 <- ggplot(data, aes()) step2 <- step1 + geom_point() step3 <- step2 + geom_smooth() step4 <- step3 + theme_classic() print(step4) }} {{pre > 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) }} {{ref_image Score-Ctest-lm.png}} !!複数の種類のデータを重ねる *クラスごととか *個人ごとに複数回のデータとか *IDカラムに種類わけの番号を振っておく(tidydata形式) *一人が8週間エッセイを書いた例(pidで並べ替えて、weekで並べ替えた) *<<データが整数になっていることを確認>> なってない場合は、as.integer() {{pre 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に {{ref_image nicest.sample-s.png}} *線が多すぎて、わかりにくいので、色を指定 aes()に color = 見出し オプションで指定。 {{pre ggplot(nicest.sample, aes(week, score, group = pid, color = pid)) + geom_point() + geom_smooth(method = "lm", se = F) }} {{ref_image nicest.sample.color.png}} !複数のグラフを別々に表示 <> オプションの追加 * <<(~pid)>> に注意 ** pid 毎に一枚ずつにするという意味 ggplot(nicest.sample, aes(week, score, group = pid)) + geom_point() + geom_smooth(method = "lm", se = F) + facet_wrap(~pid) {{ref_image nicest.sample2.png}} !!複数のグラフを配置する {{pre library("gridExtra") grid.arrange(一つ目の図, 二つ目の図, ncol=2) }} !facet !!geom_line() 折れ線グラフを重ねる * aes()で、color=IDで人ごとに色を変えるだけでなく、 * group=IDも合わせて指定することで、それぞれのIDのポイント間に線を引ける {{pre 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) }} {{ref_image sugi-iwa_ID.png}} !!geom_bar() 棒グラフを並べる {{pre ggplot(final.long.data, aes(x=category, y=value, fill=students)) + geom_bar(stat="identity", position="dodge") }} !!boxplot !geom_boxplot() !!Tips !複数のグラフの配置 * facetで並べるのではなくて、 * 個別にggplotで作成した複数のグラフをまとめて配置する。 {{pre 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")) }} !キャプションの追加 labs(caption="ここに書く") * ref: https://www.statology.org/ggplot-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="入学年度") !ラベルのいろいろ {{pre 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") }} {{ref_image labs.PNG}} !書き方のスタイル二種類 *g <- g + スタイル {{pre 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スタイル {{pre 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") !軸のメモリを具体的に設定する(連続尺度) {{pre 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) !軸のメモリを具体的に設定する(名義尺度) {{pre 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()すること {{pre 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://brain-storm.space/r_graph/962/ *https://datator.exblog.jp/24809125/ !散布図と回帰直線 *https://qiita.com/fujino-fpu/items/43b6bef969afae8b2375 *https://brain-storm.space/rggplot_scatterplot/751/ !!References *pointの変更 **https://www.datanovia.com/en/blog/ggplot-point-shapes-best-tips/ *https://qiita.com/roadricefield/items/40e92b3d78eaa5e84190 *https://stats.biopapyrus.jp/r/ggplot/ *https://www.jaysong.net/ggplot_intro2/ *https://ggplot2-book.org/ *https://heavywatal.github.io/rstats/ggplot2.html *軸の設定 **https://qiita.com/swathci/items/00b4a847843a33345887