今天繼續 跟著Nature Communications學畫圖系列第三篇。學習R語言ggplot2包畫箱線圖。
對應的 Nature Communications 的論文是 Fecal pollution can explain antibiotic resistance gene abundances in anthropogenically impacted environments
這篇論文數據分析和可視化的部分用到的數據和代碼全部放到了github上 https://github.com/karkman/crassphage_project
非常好的R語言學習素材。
論文中的figure1是使用基礎繪圖函數畫的,我感覺如果使用ggplot2實現起來可能會更容易。今天就先用ggplot2試著畫一下箱線圖。
首先是讀入數據
HMP<-read.table("data/HMP.txt")
dim(HMP)
head(HMP)
數據中有缺失值,將缺失值去掉
HMP<-na.omit(HMP)
最基本的箱線圖
library(ggplot2)
ggplot(HMP,aes(x=country,y=log10(rel_crAss)))+
geom_boxplot()
image.png
填充顏色
cols <- c("#E69F00", "#56B4E9", "#009E73")
ggplot(HMP,aes(x=country,y=log10(rel_crAss)))+
geom_boxplot(aes(fill=country))+
scale_fill_manual(values = cols)
image.png
去掉圖例、灰色背景等
ggplot(HMP,aes(x=country,y=log10(rel_crAss)))+
geom_boxplot(aes(fill=country),show.legend = F)+
scale_fill_manual(values = cols)+
theme(panel.background = element_blank(),
axis.title = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
image.png
用注釋的辦法添加一條坐標軸
ggplot(HMP,aes(x=country,y=log10(rel_crAss)))+
geom_boxplot(aes(fill=country),show.legend = F)+
scale_fill_manual(values = cols)+
theme(panel.background = element_blank(),
axis.title = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())+
annotate(geom="segment",x=1,xend=3,y=-4,yend=-4)+
scale_y_continuous(expand = c(0,0))
image.png
添加誤差線
ggplot(HMP,aes(x=country,y=log10(rel_crAss)))+
geom_boxplot(aes(fill=country),show.legend = F)+
scale_fill_manual(values = cols)+
theme(panel.background = element_blank(),
axis.title = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())+
annotate(geom="segment",x=1,xend=3,y=-4,yend=-4)+
scale_y_continuous(expand = c(0,0))+
stat_boxplot(geom = "errorbar", aes(ymin = ..ymax..),width=0.2)+
stat_boxplot(geom = "errorbar", aes(ymax = ..ymin..),width=0.2)
image.png
翻轉、更改刻度的長度
ggplot(HMP,aes(x=country,y=log10(rel_crAss)))+
geom_boxplot(aes(fill=country),show.legend = F)+
scale_fill_manual(values = cols)+
theme(panel.background = element_blank(),
axis.title = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.length.y = unit(0.3,'cm'))+
annotate(geom="segment",x=1,xend=3,y=-4,yend=-4)+
scale_y_continuous(expand = c(0,0))+
stat_boxplot(geom = "errorbar", aes(ymin = ..ymax..),width=0.2)+
stat_boxplot(geom = "errorbar", aes(ymax = ..ymin..),width=0.2)+
coord_flip()
image.png
文末總結
要做到和原圖一樣的話ggplot2使用的代碼偏多了。相對來說基礎繪圖函數代碼更簡單。但是使用ggplot2話后續的美化可能會更加方便。
歡迎大家關注我的公眾號
小明的數據分析筆記本