3 005-traffic-timeseries.py
5 A relatively elaborate example of plotting time-series acquired through calls to the Socrata API
8 from datetime import datetime
11 import matplotlib.pyplot as plt
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
20 #trim the time values off of data/times stamps, and add them to our empty dictionary
22 count_date = c['date'][:10]
23 if count_date not in daily_counts.keys():
24 daily_counts[count_date]=0
26 #we are only interested in the data from one bike counter location, so filter out the rest
29 daily_counts[c['date'][:10]] += int(c['bgt_north_of_ne_70th_total'])
33 # We'll put the counts and dates into lists we will then use in plotting
36 for key in sorted(daily_counts):
37 count_dates.append(datetime.strptime(key, '%Y-%m-%d'))
38 counts.append(daily_counts[key])
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()
47 temp_date = c['day'][:10]
48 daily_temps[temp_date]=c['top_temp']
52 for key in sorted(daily_temps):
53 temp_dates.append(datetime.strptime(key, '%Y-%m-%d'))
54 temps.append(daily_temps[key])
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)
64 # A picture is worth 1000 words.
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
69 # Plot a series of figures with this relationship plotted for every month in 2014