Matplotlib - Formatting Axes
Matplotlib - Formatting Axes Appearance
Section titled “Matplotlib - Formatting Axes Appearance”Beyond setting limits and ticks, Matplotlib offers control over various aesthetic aspects of the axes, such as scale (linear vs. logarithmic), label padding, and the appearance of the axis lines themselves (spines).
Logarithmic Scale
Section titled “Logarithmic Scale”When dealing with data that spans several orders of magnitude, a standard linear scale can compress variations in smaller values, making them hard to see. A logarithmic scale is often more appropriate in such cases.
You can set the scale of the x-axis or y-axis (or both) to logarithmic using ax.set_xscale('log') or ax.set_yscale('log').
Label Padding
Section titled “Label Padding”Sometimes, the default spacing between an axis label (e.g., ‘X Axis Title’) and the tick labels might not be sufficient, or you might want to adjust it for aesthetic reasons. You can control this spacing using the labelpad parameter within the ax.set_xlabel() or ax.set_ylabel() functions, or by accessing the axis object directly.
Axis Spines
Section titled “Axis Spines”Spines are the lines that form the border of the plotting area, connecting the tick marks. By default, Matplotlib draws spines on all four sides (top, bottom, left, right). You can customize their visibility, color, and line width, or even move their position.
Spines are accessed via the ax.spines dictionary (e.g., ax.spines['top'], ax.spines['bottom']).
Example demonstrating these formatting options:
import matplotlib.pyplot as pltimport numpy as np
# Prepare datax = np.linspace(1, 10, 100)y_exp = np.exp(x)y_pow = x**2
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# --- Plot 1: Linear Scale, Label Padding, Spine Formatting ---ax1 = axes[0]ax1.plot(x, y_exp, label=r'$e^x$')ax1.plot(x, y_pow, label=r'$x^2$')ax1.set_title("Linear Scale with Spine Formatting")
# Adjust label paddingax1.set_xlabel("X Axis", fontsize=12, labelpad=15) # Increased paddingax1.set_ylabel("Y Axis", fontsize=12, labelpad=10)
# Customize spinesax1.spines['top'].set_visible(False) # Hide top spineax1.spines['right'].set_color('red') # Make right spine redax1.spines['right'].set_linewidth(2) # Make right spine thickerax1.spines['bottom'].set_linestyle('--') # Make bottom spine dashed
ax1.legend()ax1.grid(True, alpha=0.5)
# --- Plot 2: Logarithmic Scale (Y-axis) ---ax2 = axes[1]ax2.plot(x, y_exp, label=r'$e^x$')ax2.plot(x, y_pow, label=r'$x^2$')ax2.set_title("Logarithmic Scale (Y-axis)")ax2.set_xlabel("X Axis", fontsize=12)ax2.set_ylabel("Y Axis (log scale)", fontsize=12)
# Set y-axis scale to logarithmicax2.set_yscale('log')
# Default spines, but add grid (useful with log scale)ax2.grid(True, which='both', linestyle='--', alpha=0.5) # Grid for major and minor ticksax2.legend()
plt.tight_layout()plt.show()In the first plot, we hide the top spine, color the right spine red and make it thicker, and make the bottom spine dashed. We also increase the padding for the x-axis label. In the second plot, we set the y-axis to a logarithmic scale using ax2.set_yscale('log'), which is often helpful when plotting exponential data alongside polynomial data, as it makes both trends more visible across their ranges.