心得
- charts圖表采用固定格式輸入,只要把options設(shè)好,series數(shù)據(jù)列表擺好,就能畫(huà)出圖表(目前主要看到了柱圖和折線圖兩種形式)
- 橫軸按時(shí)間展現(xiàn)時(shí),要用一個(gè)函數(shù)輸出所有單個(gè)日期元素,此時(shí)會(huì)用到datetime庫(kù)
我的代碼
import pymongo
import charts
from datetime import timedelta,date
client = pymongo.MongoClient('localhost',27017)
test = client['test']
item_info = test['sample']
#觀察庫(kù)中的數(shù)據(jù)分類(lèi)規(guī)律
for i in item_info.find({},{'_id':0,'cates':1}).limit(300):
print(i)
#給出起始日期,自動(dòng)取7天日期的函數(shù)
def get_seven_dates(the_date):
the_date = date(int(the_date.split('.')[0]),int(the_date.split('.')[1]),int(the_date.split('.')[2]))
days = timedelta(days=1)
for i in range(1,8,1):
yield the_date.strftime('%Y.%m.%d')
the_date = the_date + days
#給出起始日期和分類(lèi),自動(dòng)取7日發(fā)帖量數(shù)據(jù)列表
def get_data_within(start_date,classes):
for the_class in classes:
the_class_day_posts = []
for date in get_seven_dates(start_date):
a = list(item_info.find({'pub_date':date,'cates':the_class}))
#print('#'*20,date,the_class,len(a),'#'*20)
each_day_posts = len(a)
the_class_day_posts.append(each_day_posts)
data = {
'name':the_class,
'data':the_class_day_posts,
'type':'line'
}
yield data
#準(zhǔn)備圖表的選項(xiàng)
options = {
'chart':{'zoomType':'xy'},
'title': {'text':'七日分類(lèi)發(fā)帖量統(tǒng)計(jì)'},
'subtitle': {'text':'按時(shí)間和分類(lèi)'},
'xAxis' : {'categories':[i for i in get_seven_dates(start_date)]},
'yAxis' : {'title': { 'text' : '數(shù)量'}}
}
#圖表輸入數(shù)據(jù)
series = [ i for i in get_data_within(start_date,['北京二手手機(jī)','北京二手筆記本','北京二手臺(tái)式機(jī)/配件'])]
#畫(huà)圖表
charts.plot(series, show='inline', options = options )
運(yùn)行結(jié)果
取2015年12月22日起1周:

1.jpg
取2015年12月29日起1周:

2.jpg