在子图之间绘制一条线

时间:2013-08-12 16:59:23

标签: python matplotlib

我在Python中用Pyplot创建了一个有多个子图的图。

我想绘制一条不在任何图上的线。我知道如何画一条线作为情节的一部分,但我不知道如何在情节之间的白色空间上进行。

谢谢。


感谢您的链接,但我不希望图之间有垂直线。实际上,其中一个图上方的水平线表示某个范围。有没有办法在图形上绘制任意一条线?

1 个答案:

答案 0 :(得分: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()

enter image description here

对于绘制线条,您只需指定要用作transform的kwarg的plot(实际上,这同样适用于大多数其他绘图命令)。

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

正如@tcaswell所提到的,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

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