Python Matplotlib draws histogram and line chart at the same time

Today, a friend asked me to draw a bar chart and a line chart at the same time. I tried it and found it interesting, so I shared my code:

Data read

import pandas as pd
import matplotlib.pylab as plt
import seaborn as sns

import pylab as mpl
%matplotlib inline

df=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	2
0	教育支出	46405.0	0.148884
1	社会保障和就业支出	50327.0	0.161467
2	卫生健康支出	34327.0	0.110133
3	交通运输支出	32245.0	0.103453
4	住房保障支出	8470.0	0.027175

Drawing

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

Show off

Insert picture description here

references

Python study notes (4)-Matplotlib draws histogram and line graph at the same time

Guess you like

Origin blog.csdn.net/w5688414/article/details/115042723