matplotlib绘图

来源:互联网 发布:ubuntu 查看jdk版本 编辑:程序博客网 时间:2024/05/18 02:39

需求简述:从mongodb取出目标数据,按照日期将成都市房屋成交量以折线图的形式展示;有坐标名称,有图例;日期为x轴,成交量为y轴,如果日期过多,则部分均匀展示;新房和二手房分两个图展示。

1、日期作为x轴

参考官方示例api example code: date_demo.py

#按照月份展示坐标轴坐标x值,按照日期绘图,months = mdates.MonthLocator()  # every monthdays = mdates.DayLocator() #every daydaysFmt = mdates.DateFormatter('%Y%m%d')# format the ticksax.xaxis.set_major_locator(days) #坐标x轴实际的点ax.xaxis.set_major_formatter(daysFmt)ax.xaxis.set_minor_locator(days) #坐标x轴精简后的点#x轴字符串旋转for label in ax.get_xticklabels():    label.set_rotation(30)    label.set_horizontalalignment('right')#set min and max x,防止x轴过长,数据展示抱团timemin = x_gaoxin_new[0]timemax = x_gaoxin_new[len(x_gaoxin_new)-1]ax.set_xlim(timemin, timemax)

2、设置坐标轴名称

#set title of axisax.set_ylabel(u'成交量(套)')  ax.set_xlabel(u'交易日')  
这里遇到一个中文乱码问题,解决方案:matplotlib画图中文乱码的解决办法

a.修改matplotlibrc文件。进入Python安装目录下的Lib\site-packages\matplotlib\mpl-data目录,打开matplotlibrc文件,删除font.family和font.sans-serif两行前的#,并在font.sans-serif后添加微软雅黑字体(Microsoft YaHei)

b.代码中使用unicode编码。ax.set_xlabel(u'交易日')

3、设置图例

最开始直接使用legend,不生效,报错: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x000000001074E7F0>]Use proxy artist instead.
line1 = ax1.plot(x_gaoxin_new, y_gaoxin_new,'rs-')line2 = ax1.plot(x_all_new,y_all_new,'go-')...fig.legend((line1, line2), ('gaoxin', 'chengdu'), 'upper left')

参考官方文档legend_demo更改一种写法,能正常显示:

line1 = ax1.plot(x_gaoxin_new, y_gaoxin_new,'rs-',label=u'高新区')line2 = ax1.plot(x_all_new,y_all_new,'go-',label=u'成都市')...legend = pl.legend(loc='center', shadow=True, fontsize='x-large')# Put a nicer background color on the legend.legend.get_frame().set_facecolor('#00FFCC')

但是当后面再加一张图后,这个图例显示就会在最后一张图上显示,存在一定瑕疵,后面再解决。

4、设置图名

#设置图标题ax1.set_title(u'商品房今日成交',{},loc='center')ax2.set_title(u'二手房今日成交',{},loc='center')

5、一个画布上画多张图

首先创建一个figure对象,向后使用figure.add_axes()方法向figure添加axes即可。

fig = pl.figure()#按照[left,bottom,width,height]新建一个axes到figureax1 = fig.add_axes([0.1, 0.65, 0.85, 0.3])ax2 = fig.add_axes([0.1, 0.15, 0.85, 0.3])line1 = ax1.plot(x_gaoxin_new, y_gaoxin_new,'rs-',label=u'高新区')line2 = ax1.plot(x_all_new,y_all_new,'go-',label=u'成都市')line3 = ax2.plot(x_gaoxin_old, y_gaoxin_old,'rs-',label=u'高新区')line4 = ax2.plot(x_all_old,y_all_old,'go-',label=u'成都市')

6、效果图


7、源码

# --*-- coding: utf-8 --*--__Author__ = "Leng Fuping"__Doc__ = "chart paln sample";import numpy as npimport matplotlib.pyplot as plfrom pymongo import MongoClientimport pymongoimport matplotlib.dates as mdatesimport timeimport datetimeclient = MongoClient("localhost", 27017)db = client.housemarketingcollection  = db.housemarketingx_gaoxin_new = []y_gaoxin_new = []x_all_new = []y_all_new = []x_gaoxin_old = []y_gaoxin_old = []x_all_old = []y_all_old = []for i in  collection.find({ "type" : "商品房今日成交","dist" : "高新区"}).sort("cdate", pymongo.ASCENDING):x_gaoxin_new.append(datetime.datetime.strptime(i["cdate"], "%Y%m%d").date())y_gaoxin_new.append(int(i["harea"]))for i in  collection.aggregate([{'$match' :{ "type" : "商品房今日成交"}},{'$group':{'_id':"$cdate", 'harea' : {'$sum':'$harea'}}}, {'$sort' : {'_id':1}}]):x_all_new.append(datetime.datetime.strptime(i["_id"], "%Y%m%d").date())y_all_new.append(int(i["harea"]))for i in  collection.find({ "type" : "二手房今日成交","dist" : "高新区"}).sort("cdate", pymongo.ASCENDING):x_gaoxin_old.append(datetime.datetime.strptime(i["cdate"], "%Y%m%d").date())y_gaoxin_old.append(int(i["harea"]))for i in  collection.aggregate([{'$match' :{ "type" : "二手房今日成交"}},{'$group':{'_id':"$cdate", 'harea' : {'$sum':'$harea'}}}, {'$sort' : {'_id':1}}]):x_all_old.append(datetime.datetime.strptime(i["_id"], "%Y%m%d").date())y_all_old.append(int(i["harea"]))print(x_gaoxin_new)fig = pl.figure()#按照[left,bottom,width,height]新建一个axes到figureax1 = fig.add_axes([0.1, 0.65, 0.85, 0.3])ax2 = fig.add_axes([0.1, 0.15, 0.85, 0.3])#设置图标题ax1.set_title(u'商品房今日成交',{},loc='center')ax2.set_title(u'二手房今日成交',{},loc='center')#使用数据渲染图line1 = ax1.plot(x_gaoxin_new, y_gaoxin_new,'rs-',label=u'高新区')line2 = ax1.plot(x_all_new,y_all_new,'go-',label=u'成都市')line3 = ax2.plot(x_gaoxin_old, y_gaoxin_old,'rs-',label=u'高新区')line4 = ax2.plot(x_all_old,y_all_old,'go-',label=u'成都市')#按照月份展示坐标轴坐标x值,按照日期绘图,months = mdates.MonthLocator()  # every monthdays = mdates.DayLocator() #every daydaysFmt = mdates.DateFormatter('%Y%m%d')# format the ticksax1.xaxis.set_major_locator(days)ax1.xaxis.set_major_formatter(daysFmt)ax1.xaxis.set_minor_locator(days)#x轴字符串旋转for label in ax1.get_xticklabels():    label.set_rotation(30)    label.set_horizontalalignment('right')ax2.xaxis.set_major_locator(days)ax2.xaxis.set_major_formatter(daysFmt)ax2.xaxis.set_minor_locator(days)#x轴字符串旋转for label in ax2.get_xticklabels():    label.set_rotation(30)    label.set_horizontalalignment('right')#set min and max xtimemin = x_gaoxin_new[0]timemax = x_gaoxin_new[len(x_gaoxin_new)-1]ax1.set_xlim(timemin, timemax)#set title of axisax1.set_ylabel(u'成交量(套)')  ax1.set_xlabel(u'交易日')  ax2.set_ylabel(u'成交量(套)')  ax2.set_xlabel(u'交易日')  ax1.format_xdata = mdates.DateFormatter('%Y%m%d')ax1.grid(True)ax2.format_xdata = mdates.DateFormatter('%Y%m%d')ax2.grid(True)#设置和显示图例legend = pl.legend(loc='center', shadow=True, fontsize='x-large')# Put a nicer background color on the legend.legend.get_frame().set_facecolor('#00FFCC')pl.show()

8、TODO

a、图例只能显示在一个图中;

b、弄清楚matplotlib的关键实体

9、参考资料

matplotlib api