温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python怎样绘制堆叠条形图

发布时间:2021-12-20 09:02:42 来源:亿速云 阅读:178 作者:柒染 栏目:开发技术

python怎样绘制堆叠条形图,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

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

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

导入一组自己造的数据

data  = pd.read_excel('data.xlsx')
In [4]: data
Out[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怎样绘制堆叠条形图问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI