MathubLearn / Practice / Excel
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

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

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.