Matplotlib
Matplotlib is Python's oldest and most widely used plotting library. It gives you fine-grained control over every element of a figure, from axis tick label...
Visualizing Data with Matplotlib
Matplotlib is Python's oldest and most widely used plotting library. It gives you fine-grained control over every element of a figure, from axis tick labels to line thickness. Most other visualization libraries, including Seaborn, build on top of it.
Install with pip install matplotlib. The standard import is: import matplotlib.pyplot as plt.
The simplest plot needs just two lines: x = [1, 2, 3, 4] y = [10, 20, 15, 30] plt.plot(x, y) plt.show()
Matplotlib uses a Figure/Axes hierarchy. The Figure is the overall canvas; Axes are individual plot panels within it. Using the object-oriented interface gives you more control: fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(x, y, color='steelblue', linewidth=2, label='Revenue') ax.set_title('Monthly Revenue') ax.set_xlabel('Month') ax.set_ylabel('USD') ax.legend() plt.tight_layout() plt.savefig('revenue.png', dpi=150)
Common plot types: line (ax.plot), bar (ax.bar), scatter (ax.scatter), histogram (ax.hist), and pie (ax.pie).
Subplots let you arrange multiple charts side by side: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) ax1.bar(categories, values) ax2.scatter(x, y)
Customization options are extensive. You can set colors using hex codes ('#2196F3'), named colors ('tomato'), or colormaps (plt.cm.viridis). Markers on line plots use the marker parameter: 'o' for circles, 's' for squares, '^' for triangles.
Annotations add context directly on the chart: ax.annotate('Peak', xy=(3, 30), xytext=(2.5, 28), arrowprops=dict(arrowstyle='->'))
Practical tip: Always call plt.tight_layout() before saving. It prevents axis labels and titles from overlapping, especially in subplot grids.
Exam tip: Understand the difference between plt.show() (displays interactively) and plt.savefig() (saves to file). Calling plt.show() clears the figure, so always save before showing.