Week3 hw4:Draw a Pie Chart

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}}
]
Week3 hw4:Draw a Pie Chart_第1张图片
PipeLine

Get other parameters ready

Week3 hw4:Draw a Pie Chart_第2张图片
Parameters

Final charts and Full Code

Week3 hw4:Draw a Pie Chart_第3张图片
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)

你可能感兴趣的:(Week3 hw4:Draw a Pie Chart)