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

使用plt.savefig()保存plt.quiver()图形时箭头消失问题求助

解决Matplotlib中plt.quiver()箭头保存后消失的问题

问题原因

你使用了units="dots"参数,这个单位基于屏幕像素点计算。而plt.savefig()保存图片时的默认DPI(每英寸像素数)和绘图窗口的DPI不一致,导致箭头尺寸计算出现偏差,最终在保存的图片中无法显示箭头。

解决方案

方案1:更换箭头单位(推荐)

将quiver的units参数从"dots"改为"xy"(基于坐标轴单位),同时调整width参数适配新单位:

plt.figure(figsize=(7, 4))
levels = [4, 5, 3, 2]
x = np.linspace(0, 1, len(levels))

for i in range(len(levels) - 1):
    j = i + 1
    n1, n2 = levels[i], levels[j]
    y1, y2 = np.mgrid[0:1:n1*1j, 0:1:n2*1j]
    x1 = np.full_like(y1, x[i])
    x2 = np.full_like(y2, x[j])
    plt.quiver(x1, y1, x2-x1, y2-y1, 
              angles="xy", units="xy", scale_units="xy", 
              scale=1, width=0.002, headlength=10,
              headaxislength=10, headwidth=4)
    
yp = np.concatenate([np.linspace(0, 1, n) for n in levels])
xp = np.repeat(x, levels)
plt.plot(xp, yp, "o", ms=12)
plt.gca().axis("off")
plt.margins(0.1, 0.1)
plt.savefig(r'exp\exp4\output\nu.jpg')

方案2:统一保存时的DPI

如果需要保留units="dots",可以在savefig中指定与当前图形一致的DPI:

# 其他代码不变
plt.savefig(r'exp\exp4\output\nu.jpg', dpi=plt.gcf().dpi)

方案3:强制渲染图形后再保存

在保存前调用plt.draw(),确保所有元素完成渲染:

# 其他代码不变
plt.draw()
plt.savefig(r'exp\exp4\output\nu.jpg')

内容的提问来源于stack exchange,提问作者Shi CHEN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:31:03