首先,一个快速的方法是使用 y 坐标大于 1 的 axvspan 和 clip_on=False。不过,它会绘制一个矩形而不是一条线。
举个简单的例子:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(10))
ax.axvspan(2, 4, 1.05, 1.1, clip_on=False)
plt.show()
对于绘制线条,您只需指定您想用作 plot 的 kwarg 的 transform(实际上这同样适用于大多数其他绘图命令)。
要绘制“轴”坐标(例如,0,0 是轴的左下角,1,1 是右上角),请使用transform=ax.transAxes,并绘制图形坐标(例如,0,0 是图形窗口的左下角,而 1,1 是右上角)使用transform=fig.transFigure。
正如@tcaswell 提到的,annotate 使放置文本变得更简单,并且对于注释、箭头、标签等非常有用。您可以使用 annotate 来做到这一点(通过在点和点之间画一条线空字符串),但如果你只是想画一条线,不画更简单。
不过,对于听起来你想做的事情,你可能想做一些不同的事情。
创建一个转换很容易,其中 x 坐标使用一种转换,而 y 坐标使用不同的转换。这就是axhspan 和axvspan 在幕后所做的事情。对于您想要的东西,它非常方便,其中 y 坐标固定在轴坐标中,x 坐标反映数据坐标中的特定位置。
以下示例说明了仅绘制轴坐标与使用“混合”变换之间的区别。尝试平移/缩放两个子图,注意会发生什么。
import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
fig, (ax1, ax2) = plt.subplots(nrows=2)
# Plot a line starting at 30% of the width of the axes and ending at
# 70% of the width, placed 10% above the top of the axes.
ax1.plot([0.3, 0.7], [1.1, 1.1], transform=ax1.transAxes, clip_on=False)
# Now, we'll plot a line where the x-coordinates are in "data" coords and the
# y-coordinates are in "axes" coords.
# Try panning/zooming this plot and compare to what happens to the first plot.
trans = blended_transform_factory(ax2.transData, ax2.transAxes)
ax2.plot([0.3, 0.7], [1.1, 1.1], transform=trans, clip_on=False)
# Reset the limits of the second plot for easier comparison
ax2.axis([0, 1, 0, 1])
plt.show()
平移前
平移后
请注意,对于底部图(使用“混合”变换),线位于数据坐标中并随着新的坐标区范围移动,而顶部线位于坐标区坐标中并保持固定。