Closed ixxmu closed 1 week ago
Nature Communications同款 | 桑基图
今天复现发在Nature Communications上的一篇微生物研究文章中的桑基图,也算一类累积柱状图,如下所示。
数据准备
文件test.txt,三列即可。我这3列分别为sample、type、percentage(注意:和脚本里是对应的),对应的是图的x轴、y轴和y轴的绘图数值。
脚本实现
library(ggplot2)
library(gtools)
library(ggalluvial)
#读取数据
df <- read.delim("test.txt", header = T, sep = '\t', check.names=F)
##转成因子类型,使得图中x轴和y轴的数据都按照我们输入数据的顺序出图
df$type = factor(df$type, levels = unique(df$type))
df$sample = factor(df$sample, levels = unique(df$sample))
##绘图
p <- ggplot(as.data.frame(df), aes(x = sample, y = percentage, fill = type, stratum = type, alluvium = type)) +
geom_flow(width = 0.5, alpha = 0.3, knot.pos=0, color = 'white') +
geom_col(width = 0.5, color = 'white') +
scale_y_continuous(expand = c(0, 0)) +
scale_fill_manual(values = c("#dbdbdb","#ffe699","#a9d18e","#8faadc")) + #自定义颜色
xlab("") + ylab("Explained variation (%)") + #设置x轴标题和y轴标题
theme_classic() +
theme(axis.text.x = element_text(size = 18), #设置x轴标签字体大小
axis.text.y = element_text(size = 18), #设置y轴标签字体大小
axis.title.y = element_text(size = 18), #设置x轴标题字体大小
legend.text=element_text(size=18), #设置图例标签字体大小
legend.title = element_blank(), #不展示图例标题
legend.key.spacing.y = unit(20, "pt"), #调整图例标签的间距
plot.margin = unit(c(10, 10, 10, 10), "pt") #调整图形到画布边缘的距离
)
#保存图片
ggsave("test.pdf", p, width = 8, height = 5)
有数位小伙伴询问过,我再次说下,我写的那30多篇文献Figure复现的推文都是用R语言绘制的。其实真心希望搞科研的年轻人们,会点R或者Python。现在数据一大把,还是靠自己最靠谱!工具书得有,当然网上课程一堆,只要想学,就能学会!
结果展示
参考文献
文献Figure用R画
点击公众号进入,底部菜单栏【挖到干货】里的【期刊同款图】查看!持续更新,代码大放送!推文中脚本现成的,直接copy!
不做生信小迷糊
我曾踏月而来,只因你在山中
https://mp.weixin.qq.com/s/mjW6lJoiIVJaCV3hNizoxA