From 0a6b1b4db717da540e57c15eb7506d2d8f75da58 Mon Sep 17 00:00:00 2001 From: arokem Date: Thu, 7 May 2015 16:07:18 -0700 Subject: [PATCH] Add another, more complicated plotting example. --- 001-hello-plot.py | 4 ++-- 002-subplots.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 002-subplots.py diff --git a/001-hello-plot.py b/001-hello-plot.py index ef749ff..227b56c 100644 --- a/001-hello-plot.py +++ b/001-hello-plot.py @@ -7,7 +7,7 @@ A first plot with matplotlib """ import matplotlib.pyplot as plt -figure = plt.figure() -axis = figure.add_subplot(111) +figure, axis = plt.subplots(1) plt.plot([1,2,3], [1,2,3]) plt.show() + diff --git a/002-subplots.py b/002-subplots.py new file mode 100644 index 0000000..0c6749b --- /dev/null +++ b/002-subplots.py @@ -0,0 +1,36 @@ +""" + +Make a slightly more elaborate plot with subplots + +Save the figure in the end + +""" +import matplotlib.pyplot as plt +import math + +# Make some data to plot +x = [] +y1 = [] +y2 = [] + +for i in range(100): + x.append(i) + y1.append(math.sin(i * (2 * math.pi / 100))) + y2.append(math.cos(i * (2 * math.pi/ 100))) + +# First, create an empty figure with 2 subplots +# - The function plt.subplots returns an object for the figure and for each axes +# - There are multiple ways to accomplish this same goal, but this is probably the +# simplest - notice that each subplot is associated with one of the axes objects. +fig, (ax1, ax2) = plt.subplots(2) + +# Next, put one line on the first axis and both lines on the second axis +# - On the second axes, add a legend to distinguish the two lines +ax1.plot(x, y1) + +ax2.plot(x, y1, label='sin') # The labels are what appear in the legend +ax2.plot(x, y2, label='cos') +ax2.legend() + +# Finally, save the figure as a png file +fig.savefig('myfig.png') \ No newline at end of file -- 2.39.5