Plotting with matplotlib in Python
Effective plots are important to synthesize the information into relevant and persuasive information. The following tutorial details some of the common data plotting functions within Python.
Tutorial Source Code
x = np.linspace(0,6,100)
y = np.sin(x)
z = np.cos(x)
import matplotlib.pyplot as plt
plt.plot(x,y,'r--',linewidth=3)
plt.plot(x,z,'k:',linewidth=2)
plt.legend(['y','z'])
plt.xlabel('x')
plt.ylabel('values')
plt.xlim([0, 3])
plt.ylim([-1.5, 1.5])
plt.savefig('myFigure.png')
plt.savefig('myFigure.eps')
plt.show()
If using the iPython notebook, exclude the command plt.show() and include %matplotlib inline before loading matplotlib.pyplot as shown below.
x = np.linspace(0,6,100)
y = np.sin(x)
z = np.cos(x)
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(x,y,'r--',linewidth=3)
plt.plot(x,z,'k:',linewidth=2)
plt.legend(['y','z'])
plt.xlabel('x')
plt.ylabel('values')
plt.xlim([0, 3])
plt.ylim([-1.5, 1.5])
plt.savefig('myFigure.png')
plt.savefig('myFigure.eps')
Additional Tutorials
This tutorial can also be completed with scripting programming languages like Excel and MATLAB. Click on the appropriate link for additional information and source code.
Generate a BYU Football field with Python.
Generative AI Learning
From this class forward, AI-generated code is a legitimate tool - used with the full pattern: you specify, it generates, you verify, you defend the result. Plotting is the ideal first practice: generated plot code is easy to audit because the figure shows you what it did.
Modern data: A one-day solar generation curve (power vs hour, cloudy day and clear day on the same axes) is a two-line matplotlib exercise that also teaches the domain: the AI can generate the plotting code, but only you can say whether the curve's shape, units, and peak make physical sense.
What to Turn In
Submit a short report (PDF, 1-2 pages) that curates your results into a demonstration of what you learned. You may use Generative AI to help write the report, but you must guide it to the correct visualizations, justifications, and assumptions. Answer these questions:
- Include one publication-quality figure you coded yourself (two curves, labels with units, legend, title, saved to PNG) and the code that made it.
- Include the spec you gave the AI, the generated code, and the resulting figure. List the unspecified choices the AI made - which one would have misled a reader if you had not caught it?
- Iterate the spec once: what did you add, and show the improved figure. What does this teach about specifications in general?
- From the quiz prompt: one question you missed and the corrected answer.
