Python 是否可以在matplotlib中的各个子地块周围添加边框或边框?

Python 是否可以在matplotlib中的各个子地块周围添加边框或边框?,python,matplotlib,Python,Matplotlib,我想创建一个这样的图像,但我无法将单个绘图放在一个框架内。我不知道为什么你会受到其他人的如此多的抨击。你的问题非常清楚,但解决办法绝不是。在谷歌的前两个页面上,我找不到任何解释Axis进程的东西,我知道我在寻找什么 无论如何,图形和轴都有一个面片属性,即构成背景的矩形。因此,设置图形框架非常简单: import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 1) # add a bit more breathing room aro

我想创建一个这样的图像,但我无法将单个绘图放在一个框架内。

我不知道为什么你会受到其他人的如此多的抨击。你的问题非常清楚,但解决办法绝不是。在谷歌的前两个页面上,我找不到任何解释Axis进程的东西,我知道我在寻找什么

无论如何,图形和轴都有一个面片属性,即构成背景的矩形。因此,设置图形框架非常简单:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 1)

# add a bit more breathing room around the axes for the frames
fig.subplots_adjust(top=0.85, bottom=0.15, left=0.2, hspace=0.8)

fig.patch.set_linewidth(10)
fig.patch.set_edgecolor('cornflowerblue')

# When saving the figure, the figure patch parameters are overwritten (WTF?).
# Hence we need to specify them again in the save command.
fig.savefig('test.png', edgecolor=fig.get_edgecolor())
现在,轴是一个更难破解的螺母。我们可以使用与@jody klymak建议的图形相同的方法,但是,面片仅对应于轴限制内的区域,即它不包括记号标签、轴标签或标题

然而,Axis有一个get_tightbox方法,这就是我们所追求的。然而,正如代码注释中所解释的,使用它也有一些缺陷

# We want to use axis.get_tightbbox to determine the axis dimensions including all
# decorators, i.e. tick labels, axis labels, etc.
# However, get_tightbox requires the figure renderer, which is not initialized
# until the figure is drawn.
plt.ion()
fig.canvas.draw()

for ii, ax in enumerate(axes):
    ax.set_title(f'Title {ii+1}')
    ax.set_ylabel(f'Y-Label {ii+1}')
    ax.set_xlabel(f'X-Label {ii+1}')
    bbox = ax.get_tightbbox(fig.canvas.renderer)
    x0, y0, width, height = bbox.transformed(fig.transFigure.inverted()).bounds
    # slightly increase the very tight bounds:
    xpad = 0.05 * width
    ypad = 0.05 * height
    fig.add_artist(plt.Rectangle((x0-xpad, y0-ypad), width+2*xpad, height+2*ypad, edgecolor='red', linewidth=3, fill=False))

fig.savefig('test2.png', edgecolor=fig.get_edgecolor())
plt.show()
我发现了一些非常相似的东西,并不知怎么地配置了它

autoAxis1 = ax8i[1].axis() #ax8i[1] is the axis where we want the border 

import matplotlib.patches as ptch

rec = ptch.Rectangle((autoAxis1[0]-12,autoAxis1[2]-30),(autoAxis1[1]- 
autoAxis1[0])+18,(autoAxis1[3]- 
autoAxis1[2])+35,fill=False,lw=2,edgecolor='cyan')

rec = ax8i[1].add_patch(rec)

rec.set_clip_on(False)

代码有点复杂,但一旦我们知道矩形中括号的哪个部分在做什么,就很容易得到代码

欢迎来到堆栈溢出。请花点时间阅读。事实上,你没有表现出任何解决问题的企图。也并没有任何数据可以继续。试试ax.set_edgecolor。这不是机器学习问题,请不要垃圾邮件删除不相关的标签。@warped你们应该尝一尝你们开的药。没有任何数据可以作为这个问题的有用补充。此外,快速的谷歌搜索显示,几乎没有有用的答案。唯一接近的答案是,他们自己承认这是一份非常刻薄的工作!这可能会随着参数化的任何变化而中断。对新来的人要友善一点。@PaulBrodersen,注意了。非常感谢你的帮助和关注。我发现你的代码非常有用和简单。我还发现了与你的代码非常相似的代码,并以某种方式对其进行了配置。将fig.canvas.renderer更改为fig.canvas.get_renderer后,这项功能非常有效。