0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

棒グラフにエラーバーと散布図を重ねる

Last updated at Posted at 2022-02-16

◯複数群の平均値を示す棒グラフにSDと実数値を重ねて表現したい場合の方法を探しました。

今回は適当に作った以下のデータを使いました。

df <- read.table(pipe('pbpaste'),header=T)
df

Group Value
1 1 45
2 1 70
3 1 65
4 1 55
5 1 37
6 1 58
7 1 48
8 1 52
9 1 59
10 1 64
11 2 33
12 2 27
13 2 22
14 2 28
15 2 42
16 2 23
17 2 39
18 2 32
19 2 30
20 2 29
21 3 70
22 3 71
23 3 81
24 3 59
25 3 62
26 3 72
27 3 67
28 3 73
29 3 75
30 3 90

群ごとに平均値と標準偏差を計算する。

mean <- aggregate(Value~Group,df,mean)
sd <- aggregate(Value~Group,df,sd)

library(ggplot2)

棒グラフを作成

p1 <- ggplot(df, aes(y=Value, x=factor(Group)), group=factor(Group)) + stat_summary(fun.y="mean", geom="bar",fill="white", color="black", width=0.7)

Rplot_p1.jpeg

エラーバーを追加

p2 <- p1 + stat_summary(fun.y="mean",fun.ymin=function(x)mean(x)-sd(x), fun.ymax=function(x)mean(x)+sd(x), geom="errorbar", width=0.2)

Rplot_p2.jpeg

散布図を追加

p3 <- p2 +geom_jitter(size=2,width=0.25,height=0)

Rplot_p3.jpeg

※縦方向にずれることが発覚したためheight=0を追加(2023/02/15)

審美的パラメーターを修正して終了。

p4 <- p3 + theme_classic() + scale_y_continuous(expand=c(0,0),limits=c(0,100)) + theme(axis.title.x=element_text(size=20), axis.text.x=element_text(size=20), axis.title.y=element_text(size=20, family="Helvetica", color="black"), axis.text.y=element_text(size=20, family="Helvetica", color="black"))

Rplot_p4.jpeg

参考にしたサイト
・棒グラフに散布図を重ねる
https://datator.exblog.jp/27008169/

・審美的パラメーターの修正
https://note.com/eiko_dokusho/n/n92460465f197

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?