python绘制堆叠条形图介绍

目前在网络上多是单个条形图堆叠,没看到一组的条形图堆叠。
代码如下:

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as ticker

导入一组自己造的数据
data= https://www.it610.com/article/pd.read_excel('data.xlsx')In [4]: dataOut[4]:

python绘制堆叠条形图介绍
文章图片

多使用几个plt.bar()函数,就可以画出来啦。。。
tick_label = list(data.columns)tick_label.remove(‘类别')x = np.arange(len(tick_label))y1 = data.iloc[2,1:].values.tolist() #收入(剔除自己转入)y2 = data.iloc[3,1:].values.tolist() #支出(剔除自己转入)y3 = data.iloc[4,1:].values.tolist() #收入(自己转入)y4 = data.iloc[5,1:].values.tolist() #支出(自己转入)bar_with = 0.25 #柱体宽度plt.figure(figsize = (12,6)) #画布大小plt.bar(x, y1, width = bar_with, #柱体宽度align = ‘center', #x轴上的坐标与柱体对其的位置color = ‘orangered', alpha = 0.6, #柱体透明度label = ‘收入(剔除自己转入)')plt.bar(x,y3,width = bar_with, bottom = y1, #柱体基线的y轴坐标align = ‘center', color = ‘lightsalmon', alpha = 0.6, label = ‘收入(自己转入)')plt.bar(x + bar_with, y2, width = bar_with,align = ‘center', color = ‘deepskyblue', alpha = 0.6, label = ‘支出(剔除自己转入)')plt.bar(x + bar_with, y4, width = bar_with, bottom = y2,align = ‘center', color = ‘lightskyblue', alpha = 0.6, label = ‘支出(自己转入)')plt.title(‘月度收支表', fontsize = 10) #设置x轴标题plt.xticks(x + bar_with/2, tick_label, rotation = 70) #设置x轴坐标plt.xlabel(‘时间',fontsize = 8, verticalalignment = ‘top', horizontalalignment=‘right',rotation=‘horizontal')plt.xlabel(‘时间',fontsize = 8, verticalalignment = ‘bottom', horizontalalignment=‘center')#图例设在图形外面,控制坐标参数plt.legend(loc = ‘center', bbox_to_anchor = (0.77, 1.1), ncol=2)plt.savefig(‘draw_bar.png', dpi=200, bbox_inches = ‘tight')plt.close()

绘制如图:
python绘制堆叠条形图介绍
文章图片

是不是其实plt绘图也没有哪么辣眼睛了。。。
【python绘制堆叠条形图介绍】到此这篇关于python绘制堆叠条形图介绍的文章就介绍到这了,更多相关python堆叠条形图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读