Merge branch 'traffic-timeseries' of github.com:arokem/matplotlib-cdsw
[matplotlib-cdsw] / 002-subplots.py
1 """ 
2
3 Make a slightly more elaborate plot with subplots
4
5 Save the figure in the end
6
7 """ 
8 import matplotlib.pyplot as plt
9 import math
10
11 # Make some data to plot
12 x = []
13 y1 = []
14 y2 = []
15
16 for i in range(100):
17     x.append(i)
18     y1.append(math.sin(i * (2 * math.pi / 100)))
19     y2.append(math.cos(i * (2 * math.pi/ 100)))
20
21 # First, create an empty figure with 2 subplots
22 # - The function plt.subplots returns an object for the figure and for each axes
23 # - There are multiple ways to accomplish this same goal, but this is probably the
24 #   simplest - notice that each subplot is associated with one of the axes objects.
25 fig, (ax1, ax2) = plt.subplots(2)
26
27 # Next, put one line on the first axis and both lines on the second axis
28 # - On the second axes, add a legend to distinguish the two lines
29 ax1.plot(x, y1)
30
31 ax2.plot(x, y1, label='sin')  # The labels are what appear in the legend
32 ax2.plot(x, y2, label='cos')
33 ax2.legend()
34
35 # Finally, save the figure as a png file
36 fig.savefig('myfig.png')

Benjamin Mako Hill || Want to submit a patch?