Add an example using socrata API.
[matplotlib-cdsw] / 005-traffic-timeseries.py
1 """ 
2
3 005-traffic-timeseries.py
4
5 A relatively elaborate example of plotting time-series acquired through calls to the Socrata API
6
7 """ 
8 from datetime import datetime
9 import requests
10 import collections 
11 import matplotlib.pyplot as plt 
12
13
14 # Get traffic data:
15 api_call = requests.get("https://data.seattle.gov/resource/2z5v-ecg8.json?$where=date > '2015-01-15T00:00:00'  AND date < '2015-02-15T00:00:00'")
16 #store the data we just pulled down from the internet into a json object called 'all counts'
17 all_counts = api_call.json()
18 #create a new, empty dictionary. When we're done, this will contain counts per day
19 daily_counts = {}
20 #trim the time values off of data/times stamps, and add them to our empty dictionary
21 for c in all_counts:
22     count_date = c['date'][:10]
23     if count_date not in daily_counts.keys():
24         daily_counts[count_date]=0
25
26 #we are only interested in the data from one bike counter location, so filter out the rest
27 for c in all_counts:
28     try:
29         daily_counts[c['date'][:10]] += int(c['bgt_north_of_ne_70th_total'])
30     except:
31         pass
32
33 # We'll put the counts and dates into lists we will then use in plotting
34 count_dates = []
35 counts = []
36 for key in sorted(daily_counts):
37     count_dates.append(datetime.strptime(key, '%Y-%m-%d'))
38     counts.append(daily_counts[key])
39
40
41 # Repeat with calls to the API to get temperatures:
42 api_call_temp = requests.get("https://data.seattle.gov/resource/egc4-d24i.json?$select=date_trunc_ymd(datetime) AS day, MAX(airtemperature) AS top_temp&$where=datetime > '2015-01-15T00:00:00' AND datetime < '2015-02-15T00:00:00' AND stationname= 'RooseveltWay_NE80thSt'&$group=day")
43 raw_data = api_call_temp.json()
44 daily_temps = {}
45
46 for c in raw_data:
47     temp_date = c['day'][:10]
48     daily_temps[temp_date]=c['top_temp']
49
50 temp_dates = []
51 temps = []
52 for key in sorted(daily_temps):
53     temp_dates.append(datetime.strptime(key, '%Y-%m-%d'))
54     temps.append(daily_temps[key])
55
56 # We'll use the styles again
57 plt.style.use('ggplot') 
58 # This means: 2 rows, 1 column:
59 fig, (ax1, ax2) = plt.subplots(2, 1)
60 ax1.plot(temp_dates, temps)
61 ax2.plot(count_dates, counts)
62 plt.show()
63
64 # A picture is worth 1000 words.
65
66 # Challenge: plot a scatter plot showing this relationship. Consider using the 'scatter' plotting function:
67 # http://matplotlib.org/examples/shapes_and_collections/scatter_demo.html
68
69 # Plot a series of figures with this relationship plotted for every month in 2014

Benjamin Mako Hill || Want to submit a patch?