python matplotlib(-)柱形图

这篇博客介绍了如何利用Python的matplotlib库绘制柱状图,包括设置中文显示、创建图表、绘制不同颜色的柱子、添加标题、坐标轴标签、数值标签、图例以及调整x轴范围和网格线的方法。
  1. 准备好x轴序列和y轴序列,数组表示:
    1. and_index_ripe:x轴数组
    2. and_value_ripe:y轴数组
  2. 让matplotlib显示中文:
    1. from matplotlib.font_manager import FontManager, FontProperties  
    2. def getChineseFont():  
          return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')  
  3. import matplotlib.pyplot as plt
    1. 画布:fig = plt.figure(1,figsize= (10,10)) #figsize可选
      1. 如果要在子图中画图,先通过ax1 = plt.subplot(2,1,1); ax2 = plt.subplot(2,1,2) 画子图
      2. 然后切换到选中的子图:plt.sca(ax1)  #然后画图就是在子图上画了。
    2. plt.bar(and_index_ripe,and_value_ripe,width = 0.3,label = u'成熟',color = 'red')
      plt.bar(and_index_grow,and_value_grow,width = 0.3,label = u'成长',color = 'yellow')
    3. title : plt.title(u'xxx',fontproperties=getChineseFont())
    4. xlabel:plt.xlabel(u'xxx',fontproperties=getChineseFont())
      ylabel:plt.ylabel('count(yyy)')
    5. 设置数字标签:
      1. for a,b in zip(and_index_ripe,and_value_ripe):
            plt.text(a,b+0.05,'%.0f'%b, ha='center', va = 'bottom',fontsize = 7)
      2. 注:a,b分别表示点的位置,b+0.05表示在b上方0.05的位置显示数字标签,'%.0f'%b表示显示数字
    6. plt.legend([u'ripe','grow'])  #设置右上角标签
    7. plt.xlim(0,9)  #设置x轴范围
    8. plt.grid()   #设置背景网格
    9. plt.show()
完整代码:
# -*- coding: utf-8 -*-
%pylab inline
%matplotlib inline

import xlrd
import pylab as pl
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontManager, FontProperties  

#xlrd.Book.encoding='utf-8'

def getChineseFont():  
    return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')  

path = '/Users/wufeng/JOBS/xxx.xlsx'
book = xlrd.open_workbook(path)
table = book.sheets()[0]

nrows = table.nrows
ncols = 4
#print table.name
#print table.ncols
#print table.number
age_and = []
age_ios = []
tmp1=[]
tmp2=[]
for i in range(nrows):
    if i == 0 :
        pass
    if table.cell(i,0).value == 'android' :
        tmp1=[]
        for j in range(ncols):
            tmp1.append(table.cell(i,j).value)
        #print i,tmp1[0],tmp1[1],tmp1[2],tmp1[3]
        age_and.append(tmp1)
    elif table.cell(i,0).value == 'ios':
        tmp2=[]
        for j in range(ncols):
            tmp2.append(table.cell(i,j).value)
        #print i,tmp2[0],tmp2[1],tmp2[2],tmp2[3]
        age_ios.append(tmp2)

#print age_and
mat_and = np.matrix(age_and)
#print age_ios
mat_ios = np.matrix(age_ios)


# 先绘制android
# rects1 = plt.bar(index, scores[0], bar_width, color='#0072BC', label=names[0])
# x轴表示年龄分布(其中包含没有年龄标记的用户),y轴表示数量
# 0-成长、1-成熟、2-忠实、3-衰退、4-流失、5-当天新激活
# 0-20以下、1-20~25、2-25~30、3-30~35,4-35~40,5-40以上
and_index_ripe = [];and_value_ripe = []
and_index_grow = [];and_value_grow = []
#and_index_loyal = [];and_vlaue_loyal=[]
#and_index_loss = [];and_value_loss=[]
#and_index_new = [];and_value_new=[]
for i in range(len(age_and)):
    #print age_and[i][1], age_and[i][2]
    if age_and[i][1] == u'成熟' :
        and_value_ripe.append(int(age_and[i][3]))
        if age_and[i][2] == u'20以下' :
            and_index_ripe.append(1-0.3)
        elif age_and[i][2] == u'20~25':
            and_index_ripe.append(2-0.3)
        elif age_and[i][2] == u'25~30':
            and_index_ripe.append(3-0.3)
        elif age_and[i][2] == u'30~35':
            and_index_ripe.append(4-0.3)
        elif age_and[i][2] == u'35~40':
            and_index_ripe.append(5-0.3)
        elif age_and[i][2] == u'40以上':
            and_index_ripe.append(6-0.3)
        else:
            and_index_ripe.append(7-0.3)
    elif age_and[i][1] == u'成长' :
        and_value_grow.append(int(age_ios[i][3]))
        if age_and[i][2] == u'20以下':
            and_index_grow.append(1)
        elif age_and[i][2] == u'20~25':
            and_index_grow.append(2)
        elif age_and[i][2] == u'25~30':
            and_index_grow.append(3)
        elif age_and[i][2] == u'30~35':
            and_index_grow.append(4)
        elif age_and[i][2] == u'35~40':
            and_index_grow.append(5)
        elif age_and[i][2] == u'40以上':
            and_index_grow.append(6)
        else:
            and_index_grow.append(7)


# 创建图表
fig1 = plt.figure(1,figsize=(19, 12))
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
plt.sca(ax1)
# 先绘制成熟bar
print and_index_ripe
print and_value_ripe
name_list = ['null','~20','20~25','25~30','30~35','35~40','40~','no']
plt.xticks((0,1,2,3,4,5,6,7),('','~20','20~25','25~30','30~35','35~40','40~','no'))
plt.bar(and_index_ripe,and_value_ripe,width = 0.3,color = 'red')
plt.bar(and_index_grow,and_value_grow,width = 0.3,color = 'yellow')
plt.title(u'安卓-各生命周期年龄分布',fontproperties=getChineseFont())
#plt.xlabel('age-distribution')
plt.xlabel(u'年龄分布',fontproperties=getChineseFont())
plt.ylabel('count(id)')
for a,b in zip(and_index_ripe,and_value_ripe):
    plt.text(a,b+0.05,'%.0f'%b, ha='center', va = 'bottom',fontsize = 7)
plt.legend([u'ripe','grow'])
plt.xlim(0,9)
plt.grid()
#plt.savefig('/Users/wufeng/000-android.png')
plt.sca(ax2)
plt.plot([1,2],[2,3])
plt.show()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值