CSCI 127 Joy and Beauty of Data · Unit 4: Data science · on Final exam (Exam 3)
4.2 matplotlib
Study notes for matplotlib in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.
Big ideas
import matplotlib.pyplot as plt. The usual recipe: prepare x and y data, call a plot function, add labels, thenplt.show()(orsavefig).- Plot types:
plt.plot(x, y)lines,plt.scatter(x, y)points,plt.bar(labels, heights),plt.hist(values, bins=10),plt.pie(sizes, labels=...). - Dress it up:
plt.title, plt.xlabel, plt.ylabel, plt.legend()(needslabel=on each series),plt.grid(True), colors and markers ("ro--"). - Several series: call plot twice before show. Several panels:
fig, axes = plt.subplots(1, 2)thenaxes[0].plot(...). - A good chart answers one question: pick the type that shows it (trend over time = line, category comparison = bar, distribution = histogram, relationship = scatter).
Code you should know
Line and scatter with labels
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 50)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), "r--", label="cos")
plt.scatter([2, 5, 8], [0.9, -0.9, 0.99], color="black", label="samples")
plt.title("Waves")
plt.xlabel("x")
plt.ylabel("value")
plt.legend()
plt.grid(True)
plt.show()Output
A chart appears in the picture pane.
Bar chart and histogram side by side
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
axes[0].bar(["Mon", "Tue", "Wed", "Thu"], [3, 7, 4, 6], color="seagreen")
axes[0].set_title("Study hours")
rolls = np.random.randint(1, 7, size=300)
axes[1].hist(rolls, bins=6, edgecolor="white")
axes[1].set_title("300 dice rolls")
plt.tight_layout()
plt.show()Output
Two panels.
Worked example
You have monthly temperatures for two cities. Which plot type and which calls give a labeled comparison?
Show the solution
A line plot with two series:
plt.plot(months, city_a, label="A"), plt.plot(months, city_b, label="B"), then plt.xlabel, plt.ylabel, plt.title, plt.legend(), plt.show().Common mistakes
- Calling
plt.legend()without giving each series alabel. - Forgetting
plt.show()in a script, so nothing appears. - Plotting x and y of different lengths (ValueError).
Exam tipMemorize the five-line recipe: import, plot, label, legend, show. On the exam you may write it from scratch.
Keep going in Mathub
Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.