Matplotlib:一张图同时展示柱状图和直线图

项目中要做数据分析,将客户按照信用卡使用率划分了几段,每段统计好人数,用柱状图展示,并计算每段逾期率,用直线表示。

代码中的数据已处理。

#python 画柱状图折线图
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mtick  
from matplotlib.font_manager import FontProperties

a = [18481,12583,710,102,50,39]
b = [0.65,1.6,3.9,0.3,0.2,0.6]
l=[i for i in range(6)]

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

fmt='%.2f%%'
yticks = mtick.FormatStrFormatter(fmt)  #设置百分比形式的坐标轴
lx=[u'0次',u'1次',u'2次',u'3次',u'4次',u'4次以上']

fig = plt.figure()  
ax1 = fig.add_subplot(111)  
ax1.plot(l, b,'or-',label=u'拒绝率');
ax1.yaxis.set_major_formatter(yticks)
for i,(_x,_y) in enumerate(zip(l,b)):  
    plt.text(_x,_y,b[i],color='black',fontsize=10,)  #将数值显示在图形上
ax1.legend(loc=1)
ax1.set_ylim([-0.5, 5]);
ax1.set_ylabel('拒绝率');
plt.legend(prop={'family':'SimHei','size':8})  #设置中文
ax2 = ax1.twinx() # this is the important function  
plt.bar(l,a,alpha=0.3,color='blue',label=u'区间总人数')  
ax2.legend(loc=2)
ax2.set_ylim([0, 31000])  #设置y轴取值范围
plt.legend(prop={'family':'SimHei','size':8},loc="upper left") 
plt.xticks(l,lx)
plt.show()

猜你喜欢

转载自blog.csdn.net/opp003/article/details/89789226