使用matplotlib画堆积图并保存

源代码:

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()

效果图

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值