2017-08-01 36 views
0

我想彩色邊框添加一些次要情節與像素指定一個固定的寬度。我寫了下面的函數來爲軸後面的圖形添加一個Rectangle補丁。如何添加一個固定寬度的邊框插曲

def add_subplot_border(ax, width=0, color=None): 
    fig = ax.get_figure() 

    # Convert bottom-left and top-right to display coordinates 
    x0, y0 = ax.transAxes.transform((0, 0)) 
    x1, y1 = ax.transAxes.transform((1, 1)) 

    # Adjust margins 
    x0 -= width 
    x1 += width 
    y0 -= width 
    y1 += width 

    # Convert back to Axes coordinates 
    x0, y0 = ax.transAxes.inverted().transform((x0, y0)) 
    x1, y1 = ax.transAxes.inverted().transform((x1, y1)) 

    rect = plt.Rectangle((x0, y0), x1-x0, y1-y0, 
         color=color, 
         transform=ax.transAxes, 
         zorder=-1) 

    fig.patches.append(rect) 

這似乎是一個很好的起點,但如果這個數字被調整的邊界的相對厚度也發生了變化。如何指定一個變換來縮放和轉換補丁,使其顯示爲固定寬度邊框,而不管窗口縮放比例如何?或者,有沒有更好的方法來解決這個問題?

原始圖

Original figure

縮放圖 - 邊境

Scaled figure

+1

如何着色軸本身,而不是墊層有色'Rect'?請參閱[本答案](https://stackoverflow.com/a/12059429/2454357)瞭解如何操作。另請參閱[本答案](https://stackoverflow.com/a/2557264/2454357)瞭解如何設置軸的線寬。 –

+0

@ThomasKühn這可能是一個很好的解決了我的眼前問題,但我希望能延長想法顏色在整個插曲背景 – user3419537

+0

見我的回答對固定寬度的矩形。如果要爲整個子區域背景着色,可以使用'ax.set_facecolor()'。例如,見[這個答案](https://stackoverflow.com/a/23645437/2454357) –

回答

1

代替計算保證金和繪製01的不平與額外的寬度(當時獲得的由Axis重疊,你可以給Rectangle線寬度(點)是在重新縮放保存。請注意,該線始終以Rectangle的邊界爲中心,因此,如果您想繞軸指定5點框架,則應請求10(或可能爲11)的線寬。

我略作調整,你的功能,並增加了使用情況實例:

from matplotlib import pyplot as plt 

def add_subplot_border(ax, width=1, color=None): 

    fig = ax.get_figure() 

    # Convert bottom-left and top-right to display coordinates 
    x0, y0 = ax.transAxes.transform((0, 0)) 
    x1, y1 = ax.transAxes.transform((1, 1)) 

    # Convert back to Axes coordinates 
    x0, y0 = ax.transAxes.inverted().transform((x0, y0)) 
    x1, y1 = ax.transAxes.inverted().transform((x1, y1)) 

    rect = plt.Rectangle(
     (x0, y0), x1-x0, y1-y0, 
     color=color, 
     transform=ax.transAxes, 
     zorder=-1, 
     lw=2*width+1, 
     fill=None, 
    ) 
    fig.patches.append(rect) 


if __name__ == '__main__': 
    fig,axes = plt.subplots(ncols=2,nrows=2,figsize=(8,8)) 

    colors = 'brgy' 
    widths = [1,2,4,8] 

    for ax,col,w in zip(axes.reshape(-1),colors, widths): 
     add_subplot_border(ax,w,col) 

    plt.show() 

這是原來的數字:

subplots with rectangle-underlay

,這是縮放圖形(線看起來更細,因爲我增加了的數字大小):

scaled version of same figure

+0

不完美(可能是因爲我使用了'figure.autolayout'),但是對我所擁有的東西有很好的改進。謝謝 – user3419537

+0

@ user3419537如果你告訴我需要改進什麼,我可以嘗試着解決它。 –

+0

線的寬度保持現在固定的大小,而是矩形的界限在調整 – user3419537

相關問題