OGcourse_F17
OGcourse_F17 copied to clipboard
Plotting code
This issue gives some example code for making basic line plots in Python using (primarily) the matplotlib.pyplot
library, as well as some nice flexible ways to decorate those plots and save them to memory.
First import the following four libraries.
# Import libraries
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import os
import numpy as np
The matplotlib.ticker.MultipleLocator
library places grid lines on your plots in nice places. The os
library gives you a list of directory functions that work across platforms (e.g., Windows, OSX, Linux). The numpy
import is just for convenience in the big block of plotting code below.
Then I use some code that names the current directory in which you are working, cur_path
and creates a folder in that directory called images
if that folder doesn't already exist.
# Create directory if images directory does not already exist
cur_path = os.path.split(os.path.abspath(__file__))[0]
output_fldr = 'images'
output_dir = os.path.join(cur_path, output_fldr)
if not os.access(output_dir, os.F_OK):
os.makedirs(output_dir)
Lastly, I use a block of code like the following to make a line plot of multiple series with a title, legend, grid lines, tick marks, axis labels, and titles. You can explore lots of other options with the matplotlib
library.
# Make a plot of two lines
x_vals_1 = np.arange(1, 10)
x_vals_2 = np.arange(1, 10)
y_vals_1 = -0.5 * np.linspace(0, 9, 9) + 38.0
y_vals_2 = 2 * np.linspace(-1, 8, 9)
fig, ax = plt.subplots()
plt.plot(x_vals_1, y_vals_1, marker='D', label='Series 1')
plt.plot(x_vals_2, y_vals_2, marker='o', label='Series 2')
# for the minor ticks, use no labels; default NullFormatter
minorLocator = MultipleLocator(1)
ax.xaxis.set_minor_locator(minorLocator)
plt.grid(b=True, which='major', color='0.65', linestyle='-')
plt.title('Example plot of Series 1 and Series 2', fontsize=20)
plt.xlabel(r'$x$-values')
plt.ylabel(r'$y$-values')
plt.xlim((0.0, 10.0))
plt.ylim((-3.0, 20))
plt.legend(loc='upper left')
output_path = os.path.join(output_dir, 'plot_title')
plt.savefig(output_path)
# plt.show()
plt.close()
Two notes.
- The second-to-last line has the
plt.show()
command commented out. If you uncomment this, your program will stop and render the plot on your screen. The drawback to doing this is that your program will not move forward past thatplt.show()
command until you close the plot on your screen. - The last line is the
plt.close()
command. If you don't put this command in your script, the plots you create will pile up in your computer's memory, which can eventually freeze your machine. Including theplt.close()
command solves this problem.
@jfan3 @SophiaMo
Thanks! :)