python matplotlib 繪圖
參考資料寫在前面:
Python應用matplotlib繪圖簡介
Python matplotlib高級繪圖詳解
matplotlib主頁
需求簡述:從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安裝目錄下的Libsite-packagesmatplotlibmpl-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
推薦閱讀:
※如何快速了解一個行業(長文預警~)
※R語言 數據Excel的導入與導出
※數據篇(1):數據分析
※泰坦尼克號倖存者特徵分析
※第一關——數據分析社群之實踐計劃
TAG:Python | 數據分析 | Matplotlib |