Matplotlib Customization
A default matplotlib plot works, but a customized one communicates. Let's learn how to make your charts look professional — with colors, labels, legends, and styles that actually tell a story.
Colors and Styles
Matplotlib comes with built-in styles that instantly improve the look of your charts. You can also customize colors manually.
import matplotlib.pyplot as plt
plt.style.use("seaborn-v0_8-whitegrid")
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y1, color="#e74c3c", linewidth=2, label="Product A")
ax.plot(x, y2, color="#3498db", linewidth=2, linestyle="--", label="Product B")
ax.legend()
plt.show()
Use plt.style.available to see all available styles. The color parameter accepts hex codes, named colors, and RGB tuples.
Subplots
Sometimes you need multiple charts side by side. Subplots let you create a grid of plots in one figure.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
x = np.linspace(0, 10, 50)
axes[0].plot(x, np.sin(x), color="red")
axes[0].set_title("Sine")
axes[1].plot(x, np.cos(x), color="blue")
axes[1].set_title("Cosine")
axes[2].plot(x, np.tan(x), color="green")
axes[2].set_title("Tangent")
axes[2].set_ylim(-5, 5)
plt.tight_layout()
plt.show()
plt.tight_layout() prevents overlapping labels. Always use it when you have multiple subplots.
Annotations and Highlights
Annotations draw attention to specific data points. They turn a good chart into a great one by guiding the viewer's eye.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 24, 36, 40, 50]
fig, ax = plt.subplots()
ax.plot(x, y, marker="o")
ax.annotate("Peak", xy=(4, 40), xytext=(2, 45),
arrowprops=dict(arrowstyle="->", color="red"))
ax.set_title("Sales with Annotation")
plt.show()
The arrowprops dictionary controls the arrow's appearance. Use annotations to highlight key insights in your data.
Saving Plots
Once your plot looks perfect, save it as a file. Matplotlib supports PNG, SVG, PDF, and more.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(["A", "B", "C"], [10, 20, 15])
ax.set_title("Sales Report")
fig.savefig("sales_chart.png", dpi=300, bbox_inches="tight")
plt.show()
The dpi parameter controls resolution — 300 is print quality. bbox_inches="tight" removes excess whitespace around the chart.
Key Takeaways
- Built-in styles like "seaborn-v0_8-whitegrid" instantly improve appearance
- Subplots let you create multiple charts in one figure
- Annotations guide the viewer to important data points
- savefig() exports charts with configurable resolution