Week3 hw4:Draw a Pie Chart

2016-06-04  本文已影响0人  快要没时间了

Target

  1. Count how many commodities are successfully trading in One day.
  2. Sort them by their Post Location.
  3. Draw a Pie chart to analyse the result.

** Tips: **

  • Use aggregate function for advanced searching.
  • Use the database given by teacher will be much easier.

** Why we use aggregate? **
Because it's much more effective than find() function.


Here we go

First, design a Pipeline to filter out the required data.
For example, if I would like to know how many goods were sold out one day in Beijing's different post location, And show them in a descending sort.
I can use this kind pipeline.

# get the goods sold in one day
pipeline = [
    {'$match':{'$and':[{'pub_date':'2015.12.24'},{'time':1}]}},
    {'$group':{'_id':{'$slice':['$area',0,1]},'counts':{'$sum':1}}},
    {'$sort':{'counts':-1}}
]
PipeLine

Get other parameters ready

Parameters

Final charts and Full Code

Pie chart
import pymongo
import charts

client = pymongo.MongoClient('localhost', 27017)
myDB = client['ganjiDB']
myCollection = myDB['bjGanji']

# get the goods sold in one day
pipeline = [
    {'$match':{'$and':[{'pub_date':'2015.12.24'},{'time':1}]}},
    {'$group':{'_id':{'$slice':['$area',0,1]},'counts':{'$sum':1}}},
    {'$sort':{'counts':-1}}
]

# Now prepare the series
dataSeries = []
for i in myCollection.aggregate(pipeline):
    dataSeries.append([i['_id'][0],i['counts']])
print(dataSeries)

series = [
    {
        'type':'pie',
        'name':'Counts',
        'data':dataSeries
    }
]

options = {
    'chart':{'zoomType':'xy'},
    'title':{'text':'Statics for Goods sold in One Day'},
    'subtitle':{'text':'made by Jet'},
}

# Draw code
charts.plot(series,show='inline',options=options)
上一篇下一篇

猜你喜欢

热点阅读