pyplot & the Object-Oriented API
pyplot — Quick, Stateful
import matplotlib.pyplot as plt
plt.plot(x, y, label='revenue')
plt.title('Monthly Revenue')
plt.xlabel('Month')
plt.ylabel('USD')
plt.legend()
plt.savefig('chart.png', dpi=300)
plt.show()
# pyplot tracks an implicit "current axes" — fine for one quick plot,
# ambiguous once multiple figures/subplots are involvedObject-Oriented — Explicit, Scales Better
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))
axes[0].plot(x, revenue)
axes[0].set_title('Revenue')
axes[1].scatter(x, users, c=values, cmap='viridis')
axes[1].set_title('Users')
fig.tight_layout() # prevents titles/labels from overlapping
fig.savefig('report.png')
# ax.plot()/ax.set_title() are UNAMBIGUOUS about which subplot they
# affect — the recommended approach beyond a single throwaway plotCommon Chart Types
plt.hist(data, bins=30)
plt.bar(categories, values)
plt.scatter(x, y, c=values, cmap='viridis', s=sizes)
plt.style.use('ggplot') # global preset styling for everything after this callKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free