Matplotlib axhline:线宽改变线的X位置

Matplotlib axhline: linewidth changes X position of line

我观察到在 matplotlib.pyplotaxhline 中使用 linewidth 参数会产生一些奇怪的效果。我想让线条更粗,但是这个参数也让线条更宽。

例如线宽=1:

并且线宽 = 25:

这些块的 X 位置对我来说真的很不一样。我不能接受这么大的错误。你有什么想法如何在不改变 X 位置的情况下使这条线更粗吗?

如果您绘制的线条被限制在最小值和最大值之间,那么您应该使用 matplotlib.pyplot.hlines in place of matplotlib.pyplot.axhline. Moreover you can control the line endings style with capstyle 参数:

import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.hlines(y = 1, xmin = 1, xmax = 2, color = 'red', linewidth = 1, label = 'linewidth = 1, default capstyle')
ax.hlines(y = 2, xmin = 1, xmax = 2, color = 'green', linewidth = 25, capstyle = 'projecting', label = 'linewidth = 25, "projecting" capstyle')
ax.hlines(y = 3, xmin = 1, xmax = 2, color = 'blue', linewidth = 25, capstyle = 'butt', label = 'linewidth = 25, "butt" capstyle')

ax.set_xlim(-1, 4)
ax.set_ylim(-1, 5)

ax.legend(frameon = True)

plt.show()