需求:对kraken2比对报告进行统计后,取top10结果,然后绘制物种分类的百分比堆积柱状图
输入文件:
species1 | species2 | speciesn | |
sample1 | 1 | 2 | 5 |
sample2 | 2 | 3 | 6 |
sample3 | 3 | 4 | 7 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
table= pd.read_table("XXX.xls",sep="\t",index_col=0) #读取文件,并将第一列设为index
table2=table.sum(axis=1,skipna = True) #dataframe 每行求和
df=table.div(table2,axis='rows') #计算占比并存为新的dataframe
category_names =df.columns.values.tolist() #提取列名 存为list
results= df.T.to_dict('list') #行名为key 值为value 存为dic
labels = list(results.keys()) #确定x轴
data = np.array(list(results.values())) #确定数据
data_cum = data.cumsum(axis=1) #确定柱子起始位置
category_colors = plt.get_cmap('hsv')(np.linspace(0,1, data.shape[1])) #提取颜色 'hsv' 该值需根据实际情况选择
fig, ax = plt.subplots(figsize=(40, 30)) #绘图
plt.xticks(fontsize=12) #x轴坐标刻度字体大小
plt.yticks(fontsize=15) #y轴坐标刻度字体大小
ax.set_ylim(0, np.sum(data, axis=1).max()) #设置y轴范围
x_num=np.arange(len(category_names))
ax.set_xlim(min(x_num)-1,max(x_num)+1) #设置x轴范围
for i, (colname, color) in enumerate(zip(category_names, category_colors)):
heights = data[:, i]
starts = (data_cum[:, i] - heights)
ax.bar(labels, heights, bottom=starts, width=0.5,label=colname, color=color)
ax.legend(loc='right') #legend 位置
plt.show()
结果示例: