Matplotlib Basics
Create line, bar, and scatter charts — the foundation of Python data visualisation
Matplotlib is the foundational plotting library in Python. Most other libraries (seaborn, pandas .plot()) are built on top of it. Understanding matplotlib's structure makes you better at all Python charting.
Key concept: matplotlib has two interfaces: pyplot (quick charts, like MATLAB) and the object-oriented API (Figure and Axes objects). For data analyst work, pyplot is enough for quick exploration; the OO API is used for polished, publication-quality charts.
Example
Key Points
- ✓plt.figure(figsize=(width, height)) — always set size before plotting
- ✓plt.tight_layout() prevents labels from being cut off — always call it before show()
- ✓marker="o" adds data point markers on line charts
- ✓plt.savefig("chart.png", dpi=150, bbox_inches="tight") — save for reports
- ✓In Jupyter: charts appear inline without plt.show(); in scripts you need plt.show()
Practice Question
Which matplotlib function prevents axis labels and titles from being cut off at the edges?