Skip to content

Matplotlib - 网格

网格线(Grid lines)可以显著提高图的可读性,使数据点的值更容易估计,并将其与坐标轴比例尺进行比较。Matplotlib 提供了一种简单的方法来使用 ax.grid() 方法添加和自定义网格线。

调用 ax.grid(True) 将使用默认设置(通常是浅灰色实线)打开 x 轴和 y 轴的主要(major)网格线。

调用 ax.grid(False) 将关闭网格线。

ax.grid() 方法接受几个关键字参数(keyword arguments)来自定义网格线的外观:

  • visible (或位置布尔值): True 显示网格线,False 隐藏。
  • which: 指定影响哪些网格线。选项包括 'major'(默认)、'minor'(次要)或 'both'(两者)。
  • axis: 指定影响哪个坐标轴的网格线。选项包括 'x'、'y' 或 'both'(默认)。
  • color: 设置网格线的颜色(例如,'gray'、'red'、'#cccccc')。
  • linestyle (或 ls): 设置线条样式(例如,'-'、'--'、':'、'-.')。
  • linewidth (或 lw): 设置网格线的粗细。
  • alpha: 设置网格线的透明度(0.0 到 1.0)。

您可以多次调用 ax.grid() 并使用不同的设置,以便对主要/次要网格线或 x/y 网格线应用不同的样式。

示例演示不同的网格线配置:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mticker
# Prepare data
x = np.linspace(0, 10, 50)
y1 = x**2
y2 = np.exp(x / 3)
y3 = np.sin(x) * 10
fig, axes = plt.subplots(1, 3, figsize=(15, 5), sharey=False)
# --- Plot 1: Default Grid ---
axes[0].plot(x, y1, 'g', lw=2)
axes[0].grid(True) # Simple default grid
axes[0].set_title('Default Grid (grid(True))')
# --- Plot 2: Custom Major Grid ---
axes[1].plot(x, y2, 'r')
axes[1].grid(visible=True, which='major', axis='both', color='blue', linestyle='-.', linewidth=0.75, alpha=0.5)
axes[1].set_title('Custom Major Grid')
# --- Plot 3: Custom Major and Minor Grids ---
axes[2].plot(x, y3, 'purple')
# Customize major grid
axes[2].grid(visible=True, which='major', axis='y', linestyle='-', color='black', alpha=0.6)
# Customize minor grid (need minor ticks enabled first)
axes[2].yaxis.set_minor_locator(mticker.AutoMinorLocator(5)) # Add minor ticks
axes[2].grid(visible=True, which='minor', axis='y', linestyle=':', color='gray', alpha=0.4)
axes[2].set_title('Major (Y only) & Minor Grid (Y only)')
# Add labels to all for context
for ax in axes:
ax.set_xlabel('X Value')
ax.set_ylabel('Y Value')
fig.tight_layout()
plt.show()

此示例展示了:

  1. 一个启用了默认网格线的图。
  2. 一个带有自定义主要网格线(蓝色,点划线)的图。
  3. 一个仅在 y 轴上具有不同样式的主要(实心黑色)和次要(点状灰色)网格线的图。注意,需要先启用次要刻度(minor ticks)(例如,使用 MinorLocator 或 ax.minorticks_on()),次要网格线才能可见。