为了扩展barplot函数以实现堆叠条形图,您可以按照以下步骤进行:
import matplotlib.pyplot as plt
import numpy as np
def stacked_barplot(data_sets, labels, colors, **kwargs):
num_sets = len(data_sets)
num_categories = len(data_sets[0])
indices = np.arange(num_categories)
fig, ax = plt.subplots()
bottom = np.zeros(num_categories) # 用于记录每个类别的底部位置
for i in range(num_sets):
data = data_sets[i]
label = labels[i]
color = colors[i]
ax.bar(indices, data, bottom=bottom, label=label, color=color)
bottom += data # 更新底部位置
ax.set_xticks(indices)
ax.set_xticklabels(categories)
ax.set_xlabel(kwargs.get('xlabel', ''))
ax.set_ylabel(kwargs.get('ylabel', ''))
ax.set_title(kwargs.get('title', 'Stacked Barplot'))
ax.legend()
plt.show()
# 示例用法
data_sets = [[10, 15, 12, 8], [5, 8, 6, 12], [7, 9, 10, 5]]
labels = ['A', 'B', 'C']
colors = ['red', 'green', 'blue']
stacked_barplot(data_sets, labels, colors, title='My Stacked Barplot')
请注意,以上代码示例仅为演示目的,并未经过完整测试和优化。您可以根据自己的需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云