Matplotlib Basics
matplotlib is the foundational plotting library; you build a figure and show it.
Syntax
import matplotlib.pyplot as pltmatplotlib is the base plotting library. The usual import is import matplotlib.pyplot as plt.
The basic recipe
- Create data (often NumPy arrays).
- Call a plotting function like
plt.plot. - Add labels, then
plt.show().
Seeing your data as a picture is the fastest way to spot trends, outliers and mistakes.
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('A sine wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()When to use it
- An ML researcher plots training loss vs epoch to diagnose overfitting and decide when to apply early stopping.
- A data analyst generates a figure with two subplots: raw data on the left and the fitted regression line on the right for a presentation.
- A data pipeline saves a quality-check chart to disk as a PNG so it can be embedded automatically in a monitoring report.
More examples
Basic line plot
Creates a minimal line plot of training loss per epoch, the most common visualisation during model training.
import matplotlib.pyplot as plt
epochs = [1, 2, 3, 4, 5]
loss = [0.9, 0.7, 0.55, 0.45, 0.4]
plt.plot(epochs, loss, marker='o')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.show()Two subplots side by side
Creates a figure with two side-by-side axes using plt.subplots, each showing a different signal with individual titles.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(x, np.sin(x))
ax1.set_title('Sine')
ax2.plot(x, np.cos(x), color='orange')
ax2.set_title('Cosine')
plt.tight_layout()
plt.show()Save figure to file
Saves the finished figure to a PNG file with high resolution using savefig, so it can be shared or embedded in reports without being displayed interactively.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.plot(np.random.randn(50).cumsum(), label='portfolio')
ax.legend()
ax.set_title('Cumulative Returns')
fig.savefig('returns.png', dpi=150, bbox_inches='tight')
print('Saved returns.png')
Discussion