【问题标题】:Plotting a line in between subplots在子图之间绘制一条线
【发布时间】:2013-08-12 16:59:23
【问题描述】:

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

我想画一条不在任何图上的线。我知道如何画一条线,它是情节的一部分,但我不知道如何在情节之间的空白处画线。

谢谢。


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

【问题讨论】:

  • this 是你想的那种东西吗?如果是这样,那么clip_on=False 可能会有所帮助。
  • 您可以使用“手动坐标”,相对于整个绘图,为图形添加形状。那将是相对于图形高度和宽度的 0 和 1 坐标。我已经看过了(但不记得如何了,会看看)。
  • annotate 对于这个目的也很有用

标签: python matplotlib


【解决方案1】:

首先,一个快速的方法是使用 y 坐标大于 1 的 axvspanclip_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 坐标使用不同的转换。这就是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()

平移前

平移后

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

【讨论】:

  • 也可以使用ax.hlines(1.1, 0.3, 0.7, clip_on=False, transform=ax.transAxes),尽管这基本上是您使用plot 方法所做的事情。至少我觉得故意画水平线的时候用这个方法比plot更直观。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2019-08-15
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多