今天要模仿的圖片來(lái)自于論文 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)容不涉及分析過(guò)程,只討論作圖屏富。用到的示例數(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分組來(lái)映射顏色和形狀
library(ggplot2)
ggplot()+
geom_point(data=df,aes(x=PC1,y=PC2,
color=group,shape=group),
size=2)
接下來(lái)是一些簡(jiǎn)單的美化
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"))
接下來(lái)是添加分組邊界
添加分組邊界主要參考了文章
https://chrischizinski.github.io/rstats/vegan-ggplot2/
添加分組邊界用到的是
geom_polygon()
函數(shù),這里需要借助chull()
函數(shù)重新構(gòu)造一份數(shù)據(jù)宰翅。chull()
函數(shù)是我第一次接觸弃甥,具體作用我還得在學(xué)習(xí)一下,用如下代碼可以解決問(wèn)題汁讼,但是代碼具體的作用我還得再研究一下
比如給setosa這一組數(shù)據(jù)添加分組邊界
構(gòu)造一份新的數(shù)據(jù) 集
df1<-df[df$group=="setosa",][chull(
df[df$group=="setosa",c("PC1","PC2")]
),]
畫(huà)圖
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)
按照這個(gè)思路再給另外兩個(gè)品種添加分類(lèi)邊界就好了
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)
這個(gè)圖相比于論文中的圖還有一個(gè)不一樣的地方是:他畫(huà)坐標(biāo)軸是以(0,0)原點(diǎn)為中心的淆攻,那么在ggplot2里應(yīng)該如何實(shí)現(xiàn)呢?歡迎大家留言討論呀嘿架!
歡迎大家關(guān)注我的公眾號(hào)
小明的數(shù)據(jù)分析筆記本
示例數(shù)據(jù)可以直接留言獲取