跟著Nature Communications學畫圖~Figure1~ggplot2箱線圖

今天繼續 跟著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
用注釋的辦法添加一條坐標軸

這里參考了 https://stackoverflow.com/questions/33699650/how-can-i-control-the-lengths-of-the-axis-lines-in-ggplot

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話后續的美化可能會更加方便。

歡迎大家關注我的公眾號
小明的數據分析筆記本

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。