【自用】Python可视化-Matplotlib:堆积图(Stacked bar chart)

function:

matplotlib.pyplot.bar

代码:
import matplotlib.pyplot as plt
import numpy as np


# test_data

# X轴
species = (
    "species_1",
    "species_2",
    "species_3",
)

# Y轴
weight_counts = {
    "layer_1" : np.random.randint(5, 15, (3,)),
    "layer_2" : np.random.randint(5, 15, (3,)),
    "layer_3" : np.random.randint(5, 15, (3,)),
    "layer_4" : np.random.randint(5, 15, (3,)),
    "layer_5" : np.random.randint(5, 15, (3,)),
    "layer_6" : np.random.randint(5, 15, (3,)),
}

# 条形的宽度
width = 0.5

bottom = np.zeros(3)

# 设置图形参数
plt.figure(figsize=(12,15))
plt.title('Stack bar chart', fontsize=20)
plt.xlabel('Species', fontsize=14)
plt.ylabel('Number', fontsize=14)

# 绘制堆叠柱状图
for boolean, weight_count in weight_counts.items():
    plt.bar(species, weight_count, width, label=boolean, bottom=bottom)
    bottom += weight_count

# 调整图例的顺序和位置
handles, labels = plt.gca().get_legend_handles_labels()
plt.legend(handles[::-1], labels[::-1], loc="upper right")

plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值