簡體   English   中英

如何在各個子圖周圍添加邊框或框架

[英]How to add border or frame around individual subplots

我想創建這樣的圖像,但我無法將各個圖放在框架內。

在此處輸入圖像描述

我不知道為什么你會從其他人那里得到這么多的抨擊。 您的問題很清楚,但解決方案卻絕非如此。 我在谷歌的前兩頁上找不到任何解釋軸的過程的東西,我確切地知道我在找什么。

無論如何,圖形和坐標軸都有一個 patch 屬性,即構成背景的矩形。 因此,設置圖形框架非常簡單:

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方法,這就是我們所追求的。 但是,使用它也有一些問題,如代碼注釋中所述。

# 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.get_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)

代碼有點復雜,但是一旦我們知道 Rectangle() 中括號的哪一部分在做什么,就很容易得到代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM