Python 在子图之间绘制分隔符或线

Python 在子图之间绘制分隔符或线,python,matplotlib,Python,Matplotlib,我在一个图中绘制了四个子图,它们彼此共享xaxis 但是,这些子批次之间没有分隔符。 我想在他们之间划一条线。或者在这些子批次中是否可以采用任何分隔符 子批次轴之间至少应有分隔符。我认为应该如下图所示 \------------------------------------ subplot1 subplot2 ... \------------------------------------ subplot1 subplot2 ... \----------

我在一个图中绘制了四个子图,它们彼此共享xaxis

但是,这些子批次之间没有分隔符。 我想在他们之间划一条线。或者在这些子批次中是否可以采用任何分隔符

子批次轴之间至少应有分隔符。我认为应该如下图所示

\------------------------------------

  subplot1
  subplot2
  ...
\------------------------------------

  subplot1
  subplot2
  ...
\------------------------------------

  subplot1
  subplot2
  ...

\------------------------------------

我找到了一个解决方案,但不是一个完美的解决方案,但对我有效

  subplot1
  subplot2
  ...
将以下代码应用于子地块的每个对象

式中,[-1,1.5]是假设覆盖图中X轴所有区域的值。不尽相同

axes.plot([-1, 1.5], [0, 0], color='black', lw=1, transform=axes.transAxes, clip_on=False)
axes.plot([-1, 1.5], [1, 1], color='black', lw=1, transform=axes.transAxes, clip_on=False)
我尝试了另一种方法,我认为这是最完美的方法。如下面的代码所示

    trans = blended_transform_factory(self.figure.transFigure, axes.transAxes)
    line = Line2D([0, 1], [0, 0], color='w', transform=trans)
    self.figure.lines.append(line)

在上面的代码中,线条将从每个图形边缘的开始处开始,当图形大小改变时,线条将发生变化。

如果轴/子图具有诸如x标签或记号标签之类的装饰符,则无法直接找到分隔子图的线条的正确位置,这样子图就不会与文本重叠

解决这个问题的一个方法是获得轴的范围(包括装饰器),并在上范围的底部和下范围的顶部之间取平均值

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

fig, axes = plt.subplots(3,2, squeeze=False)

for i, ax in enumerate(axes.flat):
    ax.plot([1,2])
    ax.set_title('Title ' + str(i+1))
    ax.set_xlabel('xaxis')
    ax.set_ylabel('yaxis')

# rearange the axes for no overlap
fig.tight_layout()

# Get the bounding boxes of the axes including text decorations
r = fig.canvas.get_renderer()
get_bbox = lambda ax: ax.get_tightbbox(r).transformed(fig.transFigure.inverted())
bboxes = np.array(list(map(get_bbox, axes.flat)), mtrans.Bbox).reshape(axes.shape)

#Get the minimum and maximum extent, get the coordinate half-way between those
ymax = np.array(list(map(lambda b: b.y1, bboxes.flat))).reshape(axes.shape).max(axis=1)
ymin = np.array(list(map(lambda b: b.y0, bboxes.flat))).reshape(axes.shape).min(axis=1)
ys = np.c_[ymax[1:], ymin[:-1]].mean(axis=1)

# Draw a horizontal lines at those coordinates
for y in ys:
    line = plt.Line2D([0,1],[y,y], transform=fig.transFigure, color="black")
    fig.add_artist(line)


plt.show()

@SaulloCastro我试过axes.hlines(),但它无法在axes框外画线。这是一个非常好的答案,可能为我节省了几个小时的工作时间。我不知道这是否可行,或者我是否应该提出一个新问题。但是可以用不同的方式为不同的子空间的背景着色吗?Ex(地块1和地块2的第一个背景色为浅灰色,地块3-4的第二个背景色为灰色,地块5-6的第三个背景色为深灰色)。对于整个图形,我将使用fig,ax=
plt.subplot(figsize=(2,4),facecolor='grey',dpi=300)