在子图之间绘制一条线

4
我用Pyplot在Python中创建了多个子图的绘图。我想画一条不在任何一个子图上的线。我知道如何在一个子图上画一条线,但是我不知道如何在子图之间的空白处画线。谢谢。
谢谢您提供的链接,但我不想在子图之间画垂直线。实际上,我想在其中一个子图上方画一条水平线以表示某个范围。有没有办法在图形顶部绘制任意线条?

2
这是你想要的那种东西吗?如果是的话,那么 clip_on=False 可能会有所帮助。 - DSM
2
您可以使用“手动坐标”相对于整个图形来添加形状到图形中。这将是相对于图形高度和宽度的0和1坐标。我已经看到过了(但不记得在哪里看到的,会再查一下)。 - heltonbiker
1
“annotate” 对于这个目的也非常有用。 - tacaswell
1个回答

3

首先,一个快速的方法是使用axvspan,其中y坐标大于1且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()

绘制线条时,只需将您想要使用的 transform 作为 plot 的关键字参数指定即可 (实际上,大多数其他绘图命令也是如此)。

要在“轴”坐标系中绘制 (例如,0,0 是轴的左下角,1,1 是右上角),请使用 transform=ax.transAxes,要在整个图中的坐标系中绘制 (例如,0,0 是图形窗口的左下角,而 1,1 是右上角),请使用 transform=fig.transFigure

正如@tcaswell所提到的, annotate 使得放置文本变得更加简单,并且可以非常有用地添加注释、箭头、标签等。您可以使用 annotate 来绘制一条在某个点和一个空字符串之间的线,但如果您只想绘制一条直线,则不需要这么做。

不过,对于您想要做的事情,您可能需要以稍微不同的方式处理。很容易创建一个转换,在其中 x 坐标使用一个转换,y 坐标使用另一个转换。这就是axhspanaxvspan 在幕后执行的操作。这对于您希望 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()

移动前

enter image description here

移动后

enter image description here

请注意,底部图表(使用“混合”变换)中的线条是数据坐标,并随新轴范围移动,而顶部线条是轴坐标并保持不变。


2
使用 ax.hlines(1.1, 0.3, 0.7, clip_on=False, transform=ax.transAxes) 也是可行的,尽管这本质上与使用 plot 方法是相同的。至少我认为,在有意绘制水平线时,使用这种方法比使用 plot 更直观。 - sodd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接