In [1]:
# Use the traffic.read_times() function to read in "times" dict.
# Times dict has keys 0..23 for hours, values are wait-times in seconds
# for traffic at that hour over a whole year.
import traffic
times = traffic.read_times('commute-times.txt')
times
Out[1]:
{0: 922633,
1: 870481,
2: 814756,
3: 850357,
4: 895908,
5: 923887,
6: 951961,
7: 1193951,
8: 1142612,
9: 944167,
10: 914750,
11: 868584,
12: 882351,
13: 862107,
14: 897515,
15: 905037,
16: 927800,
17: 986690,
18: 918104,
19: 900906,
20: 883822,
21: 845436,
22: 844618,
23: 902191}
In [2]:
# Use traffic.div_times() to scale it down to seconds for one day.
times = traffic.div_times(times, 365)
times
Out[2]:
{0: 2527.7616438356163,
1: 2384.8794520547945,
2: 2232.2082191780823,
3: 2329.745205479452,
4: 2454.5424657534245,
5: 2531.1972602739725,
6: 2608.1123287671235,
7: 3271.0986301369862,
8: 3130.4438356164383,
9: 2586.758904109589,
10: 2506.1643835616437,
11: 2379.682191780822,
12: 2417.4,
13: 2361.93698630137,
14: 2458.945205479452,
15: 2479.5534246575344,
16: 2541.917808219178,
17: 2703.2602739726026,
18: 2515.353424657534,
19: 2468.2356164383564,
20: 2421.4301369863015,
21: 2316.26301369863,
22: 2314.0219178082193,
23: 2471.7561643835616}
In [3]:
# Plotting works on *lists* - make a len-24 "waits" list
# from the times dict.
waits = [ times[key] for key in range(24) ]
waits
Out[3]:
[2527.7616438356163, 2384.8794520547945, 2232.2082191780823, 2329.745205479452, 2454.5424657534245, 2531.1972602739725, 2608.1123287671235, 3271.0986301369862, 3130.4438356164383, 2586.758904109589, 2506.1643835616437, 2379.682191780822, 2417.4, 2361.93698630137, 2458.945205479452, 2479.5534246575344, 2541.917808219178, 2703.2602739726026, 2515.353424657534, 2468.2356164383564, 2421.4301369863015, 2316.26301369863, 2314.0219178082193, 2471.7561643835616]
In [4]:
# This is the canonical line to import matplotlib using the name "plt"
import matplotlib.pyplot as plt
# 1. Simplest: plot a 1-d list of values, no x-values specified
plt.plot(waits)
plt.show()
In [5]:
# 2. More typical, provide [ x-values ] and [ y-values ] lists
# Here we narrow the data to the hours 6..20.
# (Comprehension is not strictly needed here, but a common pattern)
plt.plot([i for i in range(4, 22)], waits[4:22])
plt.show()
In [6]:
# 3. Like above, but set size, add labels, can play with line color and width
plt.figure(figsize=(10, 5)) # figxize() unit is like 0.5 inch
plt.title('Commute times')
plt.xlabel('Hour of day')
plt.ylabel('Commute time in seconds')
plt.plot([i for i in range(4,21)], waits[4:21], color='yellow', linewidth=29)
plt.show()
In [ ]: