【问题标题】:Is it possible to add border or frame around individual subplots in matplotlib?是否可以在 matplotlib 中的各个子图周围添加边框或框架?
【发布时间】:2020-06-14 16:12:17
【问题描述】:

我想创建一个这样的图像,但我无法将各个图放在一个框架内。enter image description here

【问题讨论】:

  • 欢迎堆栈溢出。请花时间阅读this post。实际上,您没有表现出任何解决问题的尝试。也没有任何数据可以继续。
  • 试试 ax.set_edgecolor。
  • 不是machine-learning 问题,请不要向无关标签发送垃圾邮件(已删除)。
  • @warped 你应该尝尝你开的药。没有数据可以对这个问题有用。此外,快速的谷歌搜索显示几乎没有有用的答案。唯一接近is from 10 years ago 的答案是一项非常棘手的工作(他们自己承认!),可能会因参数化的任何变化而中断。对新人多一点善意。
  • @PaulBrodersen 点。

标签: python matplotlib


【解决方案1】:

我不知道你为什么会受到其他人的抨击。您的问题很清楚,但解决方案却绝非如此。我在谷歌的前两页上找不到任何解释轴的过程的东西,我确切地知道我在找什么。

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

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 建议),但是,补丁仅对应于轴范围内的区域,即它不包括刻度标签、轴标签、也不是标题。

但是,axes 有一个get_tightbbox 方法,这正是我们所追求的。但是,使用它也有一些问题,如代码 cmets 中所述。

# 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()

【讨论】:

  • ,非常感谢您的帮助和关注。我发现您的代码非常有用且简单。此外,我发现了与您的代码非常相似的代码并以某种方式对其进行了配置。
  • 这在将fig.canvas.renderer 更改为fig.canvas.get_renderer() 后完美运行。
【解决方案2】:

我发现了一些非常相似的东西,并以某种方式配置了它的作用。

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)

代码有点复杂,但是一旦我们知道 Rectangle() 中括号的哪一部分在做什么,就很容易得到代码。

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多