源代码:
import matplotlib.pyplot as plt
import numpy as np
def stacked_bar(data_entry,labels,
title = "the title of fig",
x_label = "x_label",
y_label = "y_label",
width = 0.35
):
datas = list(data_entry.values())
keys = list(data_entry.keys())
fig, ax = plt.subplots()
for i in range(len(data_entry)):
if i == 0:
ax.bar(labels, datas[0], width, align="center", label=keys[0]) #, yerr=men_std(表示误差大小)
bottom_value = datas[0]
else:
ax.bar(labels,datas[i],width,align="center",bottom=bottom_value,label=keys[i])
bottom_value = np.array(bottom_value) + np.array(datas[i])
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
# ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
if x_label != "":
ax.set_xlabel(x_label)
if y_label != "":
ax.set_ylabel(y_label)
ax.set_ylim(0,100)
ax.set_title(title)
ax.legend(bbox_to_anchor=(0.5, 1.17),ncol=int(len(data_entry)))
return plt
if __name__ == "__main__":
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
data_entry = {
"No_1": [20, 35, 30, 35, 27],
"No_2": [25, 32, 34, 20, 25],
"No_3": [55, 33, 36, 45, 48]
}
plt=stacked_bar(data_entry,labels,x_label="")
plt.savefig('stackedBar.pdf')
plt.show()
效果图