再来城市地点作为一个类目来看看各比例
要点:
- mongodb的各操作符的用法,如$in,$and,$set等,再去了解一下。
- 用charts画饼状图。
- pymongo的aggregate函数,pipeline模型,学会使用。
疑问:
为什么在画出的图中None部分显示的是Slice,有什么特殊的东西吗?
import charts,pymongo
client = pymongo.MongoClient('localhost',27017)
tongcheng = client.tongcheng
sample = tongcheng.sample
pipeline = [
{'$match':{'$and':[{'pub_date':{'$in':['2015.12.25','2015.12.27']}}]}},
{'$group':{'_id':{'$slice':['$area',1]},'counts':{'$sum':1}}},
{'$sort' :{'counts':-1}},
]
for i in sample.aggregate(pipeline):
print(i)
def gen_data(date):
pipeline = [
{'$match':{'$and':[{'pub_date':{'$in':date}}]}},
{'$group':{'_id':{'$slice':['$area',1]},'counts':{'$sum':1}}},
{'$sort' :{'counts':-1}},
]
for i in sample.aggregate(pipeline):
yield [i['_id'][0] if i['_id'] else '不明',i['counts']]
options = {
'chart' : {'zoomType':'xy'},
'title' : {'text': '饼图'},
'subtitle': {'text': '城区交易量分布'},
}
series = [
{
'type':'pie',
'name':'pie charts',
'data':[data for data in gen_data(['2015.12.25','2015.12.27'])]
}
]
charts.plot(series,show = 'inline',options = options)
输出结果:
{'_id': None, 'counts': 407}
{'_id': ['朝阳'], 'counts': 372}
{'_id': ['海淀'], 'counts': 222}
{'_id': ['丰台'], 'counts': 199}
{'_id': ['大兴'], 'counts': 104}
{'_id': ['昌平'], 'counts': 96}
{'_id': ['西城'], 'counts': 88}
{'_id': ['通州'], 'counts': 76}
{'_id': ['东城'], 'counts': 61}
{'_id': ['宣武'], 'counts': 53}
{'_id': ['顺义'], 'counts': 46}
{'_id': ['石景山'], 'counts': 34}
{'_id': ['房山'], 'counts': 34}
{'_id': ['崇文'], 'counts': 22}
{'_id': ['北京周边'], 'counts': 13}
{'_id': ['门头沟'], 'counts': 9}
{'_id': ['燕郊'], 'counts': 8}
{'_id': ['怀柔'], 'counts': 8}
{'_id': ['延庆'], 'counts': 5}
{'_id': ['密云'], 'counts': 4}
{'_id': ['平谷'], 'counts': 2}
改为’不明‘后