Skip to content

Matplotlib - 格式化坐标轴

除了设置限制范围(limits)和刻度(ticks),Matplotlib 还提供了对坐标轴各种美学方面的控制,例如比例尺(scale)(线性 linear 与对数 logarithmic)、标签内边距(label padding)以及坐标轴线本身(spines)的外观。

处理跨越多个数量级的数据时,标准线性比例尺(linear scale)会压缩较小值的变化,使其难以看清。在这种情况下,**对数比例尺(logarithmic scale)**通常更适用。

可以使用 ax.set_xscale('log') 或 ax.set_yscale('log') 将 x 轴或 y 轴(或两者)的比例尺设置为对数。

有时,坐标轴标签(例如,‘X Axis Title’)与刻度标签之间的默认间距可能不足,或者出于美观原因您可能想调整它。您可以使用 ax.set_xlabel() 或 ax.set_ylabel() 函数中的 labelpad 参数来控制此间距,或者直接访问坐标轴对象。

Spines 是构成绘图区域边框的线条,连接着刻度标记。默认情况下,Matplotlib 在所有四个侧面(顶部 top、底部 bottom、左侧 left、右侧 right)绘制 spines。您可以自定义它们的可见性、颜色和线宽,甚至移动它们的位置。

Spines 通过 ax.spines 字典访问(例如,ax.spines['top'], ax.spines['bottom'])。

示例演示这些格式化选项:

import matplotlib.pyplot as plt
import numpy as np
# Prepare data
x = 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 padding
ax1.set_xlabel("X Axis", fontsize=12, labelpad=15) # Increased padding
ax1.set_ylabel("Y Axis", fontsize=12, labelpad=10)
# Customize spines
ax1.spines['top'].set_visible(False) # Hide top spine
ax1.spines['right'].set_color('red') # Make right spine red
ax1.spines['right'].set_linewidth(2) # Make right spine thicker
ax1.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 logarithmic
ax2.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 ticks
ax2.legend()
plt.tight_layout()
plt.show()

在第一个图中,我们隐藏了顶部 spine,将右侧 spine 的颜色设置为红色并使其更粗,并将底部 spine 设置为虚线。我们还增加了 x 轴标签的内边距(padding)。在第二个图中,我们使用 ax2.set_yscale('log') 将 y 轴设置为对数比例尺,这在同时绘制指数数据和多项式数据时通常很有帮助,因为它使得这两种趋势在其范围内都更加可见。