簡體   English   中英

如何調整 matplotlib 中每隔兩行子圖之間的間距

[英]How to adjust space between every second row of subplots in matplotlib

我希望水平調整子圖之間的空間。 特別是在每隔兩行之間。 我可以使用fig.subplots_adjust(hspace=n)調整每一行。 但是是否可以將其應用於每第二行?

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (10,10))
plt.style.use('ggplot')
ax.grid(False)

ax1 = plt.subplot2grid((5,2), (0, 0))
ax2 = plt.subplot2grid((5,2), (0, 1))
ax3 = plt.subplot2grid((5,2), (1, 0))  
ax4 = plt.subplot2grid((5,2), (1, 1))
ax5 = plt.subplot2grid((5,2), (2, 0))
ax6 = plt.subplot2grid((5,2), (2, 1)) 
ax7 = plt.subplot2grid((5,2), (3, 0))
ax8 = plt.subplot2grid((5,2), (3, 1))

fig.subplots_adjust(hspace=0.9)

使用下面的子圖,我希望在第 2 行和第 3 行之間添加一個空格,並保持 rest 不變。 在此處輸入圖像描述

沒有像手動調整軸的位置這樣繁瑣的低級別黑客,我建議使用網格,但只是將一些行留空。

我試過這個:

import matplotlib.pyplot as plt

plt.figure(figsize=(10., 10.))

num_rows = 6
num_cols = 2

row_height = 3
space_height = 2

num_sep_rows = lambda x: int((x-1)/2)
grid = (row_height*num_rows + space_height*num_sep_rows(num_rows), num_cols)

ax_list = []

for ind_row in range(num_rows):
    for ind_col in range(num_cols):
        grid_row = row_height*ind_row + space_height*num_sep_rows(ind_row+1)
        grid_col = ind_col

        ax_list += [plt.subplot2grid(grid, (grid_row, grid_col), rowspan=row_height)]

plt.subplots_adjust(bottom=.05, top=.95, hspace=.1)

# plot stuff
ax_list[0].plot([0, 1])
ax_list[1].plot([1, 0])
# ...
ax_list[11].plot([0, 1, 4], c='C2')

這給出了這個結果:

示例輸出

請注意,您可以更改行數; 此外,您可以通過調整row_height / space_height比率(兩者都必須是整數)來調整空白區域的大小與子圖的比較。

您可以交織兩個網格,使每個第二個子圖之間的間距更大。

為了說明這個概念:

在此輸入圖像描述

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

n = 3 # number of double-rows
m = 2 # number of columns

t = 0.9 # 1-t == top space 
b = 0.1 # bottom space      (both in figure coordinates)

msp = 0.1 # minor spacing
sp = 0.5  # major spacing

offs=(1+msp)*(t-b)/(2*n+n*msp+(n-1)*sp) # grid offset
hspace = sp+msp+1 #height space per grid

gso = GridSpec(n,m, bottom=b+offs, top=t, hspace=hspace)
gse = GridSpec(n,m, bottom=b, top=t-offs, hspace=hspace)

fig = plt.figure()
axes = []
for i in range(n*m):
    axes.append(fig.add_subplot(gso[i]))
    axes.append(fig.add_subplot(gse[i]))

plt.show()

在此輸入圖像描述

這是進入乏味的低級黑客的解決方案

import matplotlib.pyplot as plt

def tight_pairs(n_cols, fig=None):
    """
    Stitch vertical pairs together.

    Input:
    - n_cols: number of columns in the figure
    - fig: figure to be modified. If None, the current figure is used.

    Assumptions: 
    - fig.axes should be ordered top to bottom (ascending row number). 
      So make sure the subplots have been added in this order. 
    - The upper-half's first subplot (column 0) should always be present

    Effect:
    - The spacing between vertical pairs is reduced to zero by moving all lower-half subplots up.

    Returns:
    - Modified fig
    """
    if fig is None:
        fig = plt.gcf()
    for ax in fig.axes:
        if hasattr(ax, 'get_subplotspec'):
            ss = ax.get_subplotspec()
            row, col = ss.num1 // n_cols, ss.num1 % n_cols
            if (row % 2 == 0) and (col == 0): # upper-half row (first subplot)
                y0_upper = ss.get_position(fig).y0
            elif (row % 2 == 1): # lower-half row (all subplots)
                x0_low, _ , width_low, height_low = ss.get_position(fig).bounds
                ax.set_position(pos=[x0_low, y0_upper - height_low, width_low, height_low])
    return fig


這是對上面 function 的測試:

def test_tight_pairs():

    def make_template(title):
        fig = plt.figure(figsize=(8, 6))
        for i in range(12):
            plt.subplot(6, 2, i+1)
            plt.plot([0,1], [0,1][::-1 if i%2==1 else 1])
        fig.suptitle(title)
        return fig
    
    make_template("The vertical spacing should have increased (disappeared) between (within) pairs.")
    tight_pairs(2)
    make_template("Default spacing.")
    plt.show()

test_tight_pairs()

額外說明:

  • 如果網格中的某些子圖對丟失,這也將起作用,例如對於子圖的“下三角”排列。
  • 為了在對之間保持一定距離,您可以通過添加一些填充
    • y0_upper - height_low - padding ,或
    • y0_upper - height_low - p * height_low
  • 如果 y 軸上的標簽和刻度重疊,則可能需要進行一些修復。

暫無
暫無

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

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