You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在matplotlib中以y轴坐标单位度量网格线宽度

实现方法

matplotlib默认的网格线linewidth参数单位为磅(1磅=1/72英寸),和坐标轴数据单位无关。如果要按y轴的数据单位定义网格线宽度,通过坐标转换把数据单位的长度折算为对应磅值即可实现。

完整实现代码

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots(constrained_layout=True)
# 先触发一次绘制,确保坐标转换参数计算准确
fig.canvas.draw()

ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))

# 自定义网格线宽度对应的y轴单位长度,此处示例为0.1个y轴单位
grid_width_yunit = 0.1
# 将y轴上相差grid_width_yunit的两个点转换为像素坐标
y0 = ax.transData.transform((0, 0))[1]
y1 = ax.transData.transform((0, grid_width_yunit))[1]
# 像素差折算为磅值:1英寸=72磅 = 画布dpi对应的像素值
grid_width_pt = abs(y1 - y0) * 72 / fig.dpi

ax.grid(linewidth=grid_width_pt, axis='y', which='both')
ax.set_ylim(0, 2.25)

# 可选:添加回调函数,缩放拖动坐标轴时网格线宽度自动适配y轴单位
def update_grid_width(event):
    y0 = ax.transData.transform((0, 0))[1]
    y1 = ax.transData.transform((0, grid_width_yunit))[1]
    new_width = abs(y1 - y0) * 72 / fig.dpi
    for line in ax.get_ygridlines():
        line.set_linewidth(new_width)
    fig.canvas.draw_idle()

ax.callbacks.connect('ylim_changed', update_grid_width)
plt.show()

调整代码中grid_width_yunit的数值即可自定义网格线对应的y轴单位宽度。

内容的提问来源于stack exchange,提问作者Fredrik P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:06:04