1
1

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 2021-12-25

棒グラフを作成したい際に、エクセルを使って作ることもできますが、
R上で棒グラフに各データ値を重ね合わせて、よりおしゃれな図を作りたいと思いました。

◯環境
MacOS 11.6 Big Sur
RStudio Version 1.3.1093

ggplot
library(ggplot2, lib.loc = "/Library/Frameworks/R.framework/Versions/3.3/Resources/library")

◯数値の読み込み

d1 <- read.table(pipe("pbpaste"),header=TRUE)
d1
Group Intensity

1 Before 12
2 Before 7
3 Before 9
4 Before 11
5 Before 14
6 Before 11
7 Before 10
8 Before 13
9 Before 11
10 Before 7
11 After 5
12 After 4
13 After 2
14 After 7
15 After 3
16 After 4
17 After 6
18 After 4
19 After 9
20 After 5

◯boxplotで箱ひげ図

p1<-ggplot(d1,aes(x=Group,y=Intensity))+geom_boxplot()

Rplot01.jpg

◯X軸の順序を入れ替える

levels(d1$Group)

[1] "After" "Before"

d2<-transform(d1, Group=factor(Group,levels=c("Before","After")))
levels(d2$Group)

Rplot02.jpeg

◯散布図を重ねる

p2<-p1+geom_point(aes(col=Group), size=5)

Rplot03.jpeg

p3<-p1+geom_jitter(aes(col=Group), size=5,width=0.2)

Rplot04.jpeg

◯背景とXY軸、項目ラベルの編集

p4<-p3+theme_classic()+scale_y_continuous(breaks = c(0,5,10,15),limits = c(0,15))+theme(axis.text.y = element_text(size = rel(2), family = "Helvetica", colour = "black"), axis.title.y=element_text(size = rel(2)))+theme(axis.text.x = element_text(size = rel(2), family = "Helvetica", colour = "black"), axis.title.x = element_blank())+ylab("Intensity")

Rplot05.jpeg

◯カラーパレット読み込みとプロット色の変更

library(RColorBrewer, lib.loc = "/Library/Frameworks/R.framework/Versions/3.3/Resources/library")

my_color <- adjustcolor(c("grey33","blue"),alpha=0.5)
p6<-p5+scale_color_manual(values = my_color)

Rplot06.jpeg

◯参考にしたサイト
・ggplot チートシート https://www.rstudio.com/resources/cheatsheets/
・plotのオプション https://bookdown.org/rdpeng/RProgDA/basic-plotting-with-ggplot2.html
・軸ラベルの編集 https://mukkujohn.hatenablog.com/entry/2016/10/11/220722
・X軸の順序を入れ替える https://qiita.com/kazutan/items/7840f743d642122d1219
・カラーパレットの選択 http://www.suikou.fs.a.u-tokyo.ac.jp/blog/2019/12/05/12-5-色の調整、箱ひげ図を用いて/

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?