我有一个像这样的pandas dataframe df1:
Sample_names esv0 esv1 esv2 esv3 ... esv918 esv919 esv920 esv921
pr1gluc8NH1 635 0 6222 0 ... 0 0 0 0
pr1gluc8NH2 3189 75 9045 0 ... 0 0 0 0
pr1gluc8NHCR1 0 2152 12217 0 ... 0 0 0 0
pr1gluc8NHCR2 0 17411 1315 0 ... 0 1 0 0
pr1sdm8NH1 365 7 4117 32 ... 0 0 0 0
pr1sdm8NH2 4657 18 13520 0 ... 0 0 0 0
pr1sdm8NHCR1 0 139 3451 0 ... 0 0 0 0
pr1sdm8NHCR2 1130 1439 4163 0 ... 0 0 0 0
您可以看到,有许多零值。我想绘制一个堆叠的条形图:
df1.plot(kind='bar',stacked=True)
这可以正常工作,并提供正确的条形图。但是传说很大,因为它为所有922值创造了传说。每个sample_names只有大约40-50个非零值;因此,原则上,传说可以较小。有什么方法可以使其仅以非零值打印传说?我将不胜感激任何帮助。
注意:如果有帮助,我创建了一个字典,其中每个元素是一个sample_names及其非零列的数据框。例如,我的字典V具有8个元素,每个元素都是数据框架。V [0]看起来像
Index pr1gluc8NH1
esv2 6222
esv9 4879
esv27 2050
等等(它有43个非零行)。
v [1]是相同的,但对于下一个样本。如果可能的话,我也可以使用此词典来制作图。
我遇到了一个类似的问题,创建了一个堆叠的条形图,并且仅标记一些数据以避免巨大的传说。我使用子图解决了它,并根据条件在for循环中手动设置标签,从这里和这里汲取灵感。
我重新创建了您的数据框的较小版本:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = [['pr1gluc8NH1',635,0,6222,0,23,3,543],['pr1gluc8NH2',3189,75,9045,0,55,5,66],['pr1gluc8NHCR1',0,2152,12217,0,43,67,43],['Bpr1gluc8NHCR2',0,17411,1315,0,889,56,0],['pr1sdm8NH1',365,7,4117,32,765,34,0]]
df = pd.DataFrame(data, columns = ['Sample_names','esv0','esv1','esv2','esv3','esv4','esv5','esv6'])
df = df.set_index('Sample_names')
print(df)
esv0 esv1 esv2 esv3 esv4 esv5 esv6
Sample_names
pr1gluc8NH1 635 0 6222 0 23 3 543
pr1gluc8NH2 3189 75 9045 0 55 5 66
pr1gluc8NHCR1 0 2152 12217 0 43 67 43
Bpr1gluc8NHCR2 0 17411 1315 0 889 56 0
pr1sdm8NH1 365 7 4117 32 765 34 0
然后,我迭代数据框架并从每列中绘制值,作为堆叠在先前条顶上的条图。只有没有零值的列将标签添加到传奇中。
mycolors = sns.color_palette(n_colors=10) #set color palette with seaborn colors
f, ax1 = plt.subplots()
bot_array = [] #need this for representing values already plotted
labels = df.columns.values.tolist() #get labels from column names
#Create base bar separately because it doesn't require 'bottom' value
col = df.iloc[:,0].to_list()
if float(0) in col:
ax1.bar(range(len(col)), col, label="", color=mycolors[0])
bot_array = np.array(col)
else:
ax1.bar(range(len(col)), col, label=labels[0], color=mycolors[0])
bot_array = np.array(col)
#Loop over dataframe and add each column as a new colored bar with label only if there are no zero values in that column
for i in range(1,len(df.columns)):
cur_color = mycolors[i]
col = df.iloc[:,i].to_list()
if float(0) in col:
ax1.bar(range(len(col)), col, bottom=bot_array, label="", color=mycolors[i])
bot_array = np.array(col)+bot_array
else:
ax1.bar(range(len(col)), col, bottom=bot_array, label=labels[i], color=mycolors[i])
bot_array = np.array(col)+bot_array
ax1.set_ylabel('Count')
plt.legend(loc='upper right')
堆叠的酒吧图有限的传奇