Matplotlib: Customizing Plots and Annotations
Matplotlib provides extensive control over every aesthetic aspect of a plot, allowing you to create highly customized and informative visualizations. This document covers common customization techniques, including colors, styles, labels, titles, legends, and adding annotations.
1. Figure and Axes Objects
While pyplot functions are convenient, using the Object-Oriented (OO) interface by explicitly creating Figure and Axes objects gives you more control and is generally recommended for complex plots.
Figure: The top-level container for all plot elements. It holds theAxes(the actual plots), titles, legends, etc.Axes: The actual plot area where data is drawn. A figure can contain multiple Axes.
import matplotlib.pyplot as plt
import numpy as np
# Create a figure and a set of subplots (here, just one subplot)
fig, ax = plt.subplots(figsize=(8, 6))
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Plot on the Axes object
ax.plot(x, y, label='Sine wave', color='blue', linestyle='--', linewidth=2)
# Set title and labels
ax.set_title('Customized Sine Wave', fontsize=16, color='darkred')
ax.set_xlabel('X-axis (Time)', fontsize=12, color='gray')
ax.set_ylabel('Y-axis (Amplitude)', fontsize=12, color='gray')
# Set limits
ax.set_xlim(0, 10)
ax.set_ylim(-1.2, 1.2)
# Customize ticks
ax.set_xticks(np.arange(0, 11, 1)) # Major ticks every 1 unit
ax.set_yticks([-1, -0.5, 0, 0.5, 1]) # Specific y-ticks
ax.tick_params(axis='x', rotation=45) # Rotate x-axis tick labels
ax.tick_params(axis='both', which='major', labelsize=10, length=6, width=2, colors='black')
# Add grid
ax.grid(True, linestyle=':', alpha=0.7)
# Add legend
ax.legend(loc='upper right', shadow=True, fancybox=True, fontsize='medium')
plt.tight_layout() # Adjust layout to prevent labels from overlapping
plt.show()
2. Colors, Markers, and Line Styles
You can control the appearance of lines and points in detail.
color: Can be a string (e.g., 'red', 'blue', 'green', 'cyan', 'magenta', 'yellow', 'black', 'white'), a hex color code (e.g., '#FF5733'), or an RGB tuple (e.g., (0.1, 0.2, 0.5)).linestyle(orls): '-', '--', '-.', ':', 'None'marker: 'o', 'v', '^', '<', '>', 's' (square), 'p' (pentagon), '*' (star), '+' (plus), 'x', 'D' (diamond)linewidth(orlw): Thickness of the line.markersize(orms): Size of the marker.markeredgecolor(ormec): Color of the marker edge.markerfacecolor(ormfc): Color of the marker face.alpha: Transparency (0.0 transparent to 1.0 opaque).
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 1)
y1 = x
y2 = x**2
y3 = 10 - x
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, color='#1f77b4', linestyle='-', linewidth=2, marker='o', markersize=8, label='Linear')
ax.plot(x, y2, color='orange', linestyle='--', linewidth=1.5, marker='s', markersize=6, markeredgecolor='black', markerfacecolor='yellow', alpha=0.7, label='Quadratic')
ax.plot(x, y3, color='magenta', linestyle=':', linewidth=3, marker='^', markersize=10, markeredgecolor='green', label='Decreasing')
ax.set_title('Custom Line Styles and Markers')
ax.set_xlabel('X Value')
ax.set_ylabel('Y Value')
ax.legend()
ax.grid(True)
plt.show()
3. Adding Annotations and Text
Annotations allow you to highlight specific points or regions on your plot and add descriptive text.
ax.text(x, y, s, **kwargs): Add textsat position(x, y).ax.annotate(s, xy, xytext, arrowprops, **kwargs): Annotate a pointxywith textsatxytext.arrowpropscan be used to customize the arrow connecting the text to the point.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 50)
y = np.cos(x) * np.exp(-x/5)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y, 'b-')
ax.set_title('Annotating a Damped Cosine Wave')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.grid(True)
# Add simple text
ax.text(8, 0.5, 'Some Text', fontsize=12, color='green', bbox=dict(facecolor='yellow', alpha=0.5))
# Annotate a specific point (peak)
peak_x = x[np.argmax(y)]
peak_y = np.max(y)
ax.plot(peak_x, peak_y, 'ro') # Mark the peak with a red dot
ax.annotate('Global Maximum', xy=(peak_x, peak_y), xytext=(peak_x + 1, peak_y + 0.3),
arrowprops=dict(facecolor='black', shrink=0.05, width=2),
fontsize=12, ha='center', bbox=dict(boxstyle="round,pad=0.3", fc="cyan", ec="b", lw=1, alpha=0.8))
# Annotate another point
ax.annotate('Another point', xy=(2.5, y[np.argmin(np.abs(x - 2.5))]), xytext=(1, -0.8),
arrowprops=dict(facecolor='purple', shrink=0.05, connectionstyle="arc3,rad=.2"),
fontsize=10, color='purple')
plt.show()
4. Customizing Ticks and Labels
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter, MultipleLocator
fig, ax = plt.subplots(figsize=(8, 5))
x = np.arange(0, 10.1, 0.1)
ax.plot(x, x**2, label='y = x^2')
ax.set_title('Custom Tick Formats')
ax.set_xlabel('Input Value')
ax.set_ylabel('Squared Value')
# Major ticks every 2 units on x-axis, minor every 0.5
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
# Format y-axis labels to two decimal places
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
# Customize tick parameters
ax.tick_params(axis='x', direction='inout', length=10, width=2, colors='r',
grid_color='r', grid_alpha=0.5, labelsize=10)
ax.tick_params(axis='y', direction='out', length=6, width=1, colors='b',
grid_color='b', grid_alpha=0.5, labelsize=10)
ax.grid(True, which='both', linestyle='--', alpha=0.6)
ax.legend()
plt.show()
5. Saving Plots
You can save your plots in various formats.
# To save the last plotted figure
plt.savefig('my_plot.png') # Default format is PNG
# Save with specific format and resolution
plt.savefig('my_plot.pdf', format='pdf', dpi=300)
# Save a specific figure object
fig.savefig('my_figure.svg', format='svg')
Further Topics:
- Colormaps (
cmap) for heatmaps and scatter plots. - Stylesheets (
plt.style.use()). - Text properties (font family, weight, style).
- Working with LaTeX in labels and text.
- Figure and subplot titles.
- Customizing spines (plot borders).
Mastering these customization techniques allows you to create high-quality, publication-ready visualizations that effectively communicate insights from your data.