今天要模仿的圖片來自于論文 Core gut microbial communities are maintained by beneficial interactions and strain variability in fish。期刊是 Nature microbiology

今天重復(fù)論文中Figure4中的小b這幅圖

論文中他實(shí)際做的分析是主坐標(biāo)分析(Principal coordinates analysis of samples),今天的推文內(nèi)容不涉及分析過程,只討論作圖。用到的示例數(shù)據(jù)是鳶尾花的數(shù)據(jù)集做完主成分分析的結(jié)果。需要示例數(shù)據(jù)的可以在文末留言
數(shù)據(jù)格式

第一步讀入數(shù)據(jù)
df<-read.csv('irispca.csv',row.names = 1,header=T)
head(df)

基本的散點(diǎn)圖,根據(jù)group分組來映射顏色和形狀
library(ggplot2)
ggplot()+
geom_point(data=df,aes(x=PC1,y=PC2,
color=group,shape=group),
size=2)

接下來是一些簡單的美化
ggplot()+
geom_point(data=df,aes(x=PC1,y=PC2,
color=group,shape=group),
size=3)+
theme_bw()+
theme(panel.background = element_blank(),
panel.grid = element_blank(),
legend.title = element_text(hjust=0.5))+
labs(x="Coordinate 1 (15%)",y="Coordinate 2 (8%)")+
scale_color_manual(values = c("#008080","#ffa500","#8b008b"))

接下來是添加分組邊界
添加分組邊界主要參考了文章
https://chrischizinski.github.io/rstats/vegan-ggplot2/
添加分組邊界用到的是
geom_polygon()函數(shù),這里需要借助chull()函數(shù)重新構(gòu)造一份數(shù)據(jù)。chull()函數(shù)是我第一次接觸,具體作用我還得在學(xué)習(xí)一下,用如下代碼可以解決問題,但是代碼具體的作用我還得再研究一下
比如給setosa這一組數(shù)據(jù)添加分組邊界
構(gòu)造一份新的數(shù)據(jù) 集
df1<-df[df$group=="setosa",][chull(
df[df$group=="setosa",c("PC1","PC2")]
),]
畫圖
ggplot()+
geom_point(data=df,aes(x=PC1,y=PC2,
color=group,shape=group),
size=3)+
theme_bw()+
theme(panel.background = element_blank(),
panel.grid = element_blank(),
legend.title = element_text(hjust=0.5))+
labs(x="Coordinate 1 (15%)",y="Coordinate 2 (8%)")+
scale_color_manual(values = c("#008080","#ffa500","#8b008b"))+
geom_polygon(data=df1,aes(x=PC1,y=PC2,group=group),
color="#008080",fill="#008080",alpha=0.2,size=1)

按照這個思路再給另外兩個品種添加分類邊界就好了
library(ggplot2)
table(df$group)
df1<-df[df$group=="setosa",][chull(
df[df$group=="setosa",c("PC1","PC2")]
),]
df2<-df[df$group=="versicolor",][chull(
df[df$group=="versicolor",c("PC1","PC2")]
),]
df3<-df[df$group=="virginica",][chull(
df[df$group=="virginica",c("PC1","PC2")]
),]
ggplot()+
geom_point(data=df,aes(x=PC1,y=PC2,
color=group,shape=group),
size=3)+
theme_bw()+
theme(panel.background = element_blank(),
panel.grid = element_blank(),
legend.title = element_text(hjust=0.5))+
labs(x="Coordinate 1 (15%)",y="Coordinate 2 (8%)")+
scale_color_manual(values = c("#008080","#ffa500","#8b008b"))+
geom_polygon(data=df1,aes(x=PC1,y=PC2,group=group),
color="#008080",fill="#008080",alpha=0.2,size=1)+
geom_polygon(data=df2,aes(x=PC1,y=PC2,group=group),
color="#ffa500",fill="#ffa500",alpha=0.2,size=1)+
geom_polygon(data=df3,aes(x=PC1,y=PC2,group=group),
color="#8b008b",fill="#8b008b",alpha=0.2,size=1)

這個圖相比于論文中的圖還有一個不一樣的地方是:他畫坐標(biāo)軸是以(0,0)原點(diǎn)為中心的,那么在ggplot2里應(yīng)該如何實(shí)現(xiàn)呢?歡迎大家留言討論呀!
歡迎大家關(guān)注我的公眾號
小明的數(shù)據(jù)分析筆記本
示例數(shù)據(jù)可以直接留言獲取