matplotlib is the foundation plotting library for Python. Its API is two-track: a pyplot 'state machine' interface that mimics MATLAB, and an explicit object-oriented interface that scales to complex figures. Modern practice uses the explicit fig/ax pattern even for simple plots.
The fig/ax pattern
import matplotlib.pyplot as pltfig, ax = plt.subplots(figsize=(8, 5))ax.plot(bankrates['month'], bankrates['lending_rate'], label='Lending')ax.plot(bankrates['month'], bankrates['deposit_rate'], label='Deposit')ax.set_xlabel('Month')ax.set_ylabel('Rate (%)')ax.set_title('Kenyan commercial bank rates, 2023-2024')ax.legend()plt.show()
Common plot types
ax.plot(x, y) # lineax.scatter(x, y) # scatterax.bar(x, heights) # barax.hist(values, bins=20) # histogramax.boxplot(arrays) # boxplot
Multiple subplots
fig, axes = plt.subplots(1, 2, figsize=(12, 4))axes[0].plot(x, y1)axes[0].set_title('Lending')axes[1].plot(x, y2)axes[1].set_title('Deposit')fig.tight_layout()
Pandas .plot()
Pandas wraps matplotlib in a more concise API. For exploratory plots, df.plot() is hard to beat.
bankrates.plot(x='month', y=['lending_rate', 'deposit_rate'])
Styling — keep it minimal
Resist the urge to over-style. The defaults in modern matplotlib are good. Add labels, a title, and a legend; resize for the medium; export to PNG or SVG.
When to reach for seaborn or plotly
Seaborn is matplotlib with smarter statistical defaults — quicker for distributions, regressions, and faceted plots. Plotly is interactive and ideal for dashboards. Both build on top of matplotlib for the underlying engine.
Exercise
Plot a line chart of bankrates['month'] vs bankrates['lending_rate'].