Python / Data Science Essentials Interview Questions
What is Matplotlib and what are the key components of a figure?
Matplotlib is Python's foundational plotting library, originally modelled after MATLAB's plotting API. Almost every other Python visualisation library (Seaborn, Pandas .plot(), Plotly static exports) either wraps Matplotlib or uses it as a rendering backend.
Understanding the object hierarchy is essential for customising plots beyond the defaults:
| Object | What it is | Created by |
|---|---|---|
| Figure | The entire canvas / window | plt.figure() or plt.subplots() |
| Axes | One coordinate system (plot area) inside a Figure | fig.add_subplot() or plt.subplots() |
| Axis | The X or Y axis of an Axes (note: Axes ≠ Axis) | Exists on every Axes |
| Artist | Every visible element — lines, patches, text, legends | plot(), bar(), text(), etc. |
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2 * np.pi, 300) # Object-oriented interface (recommended for complex plots) fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(x, np.sin(x), label='sin(x)', color='steelblue', linewidth=2) ax.plot(x, np.cos(x), label='cos(x)', color='tomato', linestyle='--') ax.set_title('Sine and Cosine', fontsize=14) ax.set_xlabel('x (radians)') ax.set_ylabel('Amplitude') ax.legend() ax.grid(True, alpha=0.3) ax.set_xlim(0, 2 * np.pi) fig.tight_layout() # prevent label clipping plt.savefig('trig.png', dpi=150, bbox_inches='tight') plt.show()
The pyplot (plt.*) interface is a state-machine shorthand that implicitly manages the current Figure and Axes. It is convenient for quick interactive plots but problematic in scripts and notebooks that create multiple figures — use the object-oriented fig, ax = plt.subplots() style for anything beyond a single simple chart.
More Related questions...