python Matplotlib同时画柱状图与折线图

网友投稿 351 2022-08-27

python Matplotlib同时画柱状图与折线图

今天有朋友叫我同时画柱状图和折线图,我试了一下,发现挺有意思的,所以把我的代码分享出来:

数据读取

import pandas as pdimport matplotlib.pylab as pltimport seaborn as snsimport pylab as mpl%matplotlib inlinedf=pd.read_excel('demo.xlsx',header=None)df.head()df.rename(columns={0:'zhichu',1:'money',2:'ratio'},inplace=True)df1=df.iloc[:5]

0 1 20 教育支出 46405.0 0.1488841 社会保障和就业支出 50327.0 0.1614672 卫生健康支出 34327.0 0.1101333 交通运输支出 32245.0 0.1034534 住房保障支出 8470.0 0.027175

作图

fig = plt.figure(figsize=(10,10)) label='一般公共预算重点支出情况'plt.title(label)plt.text(4, 17, r'单位:万元', fontsize=10)ax1 = fig.add_subplot(111) l=[i for i in range(5)]b=df1['ratio'].tolist()b=[round(item*100,1) for item in b]a=df1['money'].tolist()lx=df1['zhichu'].tolist()ax1.plot(l, b,'blue',label=u'增长率');ax1.yaxis.set_major_formatter(yticks)for i,(_x,_y) in enumerate(zip(l,b)): plt.text(_x,_y,a[i],color='black',fontsize=10,) #将数值显示在图形上ax2.legend(loc=1)ax2 = ax1.twinx() # this is the important function plt.bar(l,a,alpha=0.6,color='brown',label=u'支出') ax2.legend(loc=2)# ax2.set_ylim([0, 2500]) #设置y轴取值范围for i,(_x,_y) in enumerate(zip(l,a)): plt.text(_x,_y,str(b[i])+'%',color='black',fontsize=10,) #将数值显示在图形上# plt.legend(prop={'family':'SimHei','size':8},loc="upper left") plt.xticks(l,lx)plt.show()

展示

参考文献

​​Python学习笔记(4)–Matplotlib同时画柱状图与折线图​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 784. Letter Case Permutation
下一篇:ubuntu 16.04安装ROS Kinetic
相关文章

 发表评论

暂时没有评论,来抢沙发吧~