如何在网格中排列图形?

问题描述 投票:0回答:1

我有六对垂直堆叠的人物。我想将图形排列成 3x2 网格。但是,我没有找到办法。

MWE:

import matplotlib.pyplot as plt

def arrange_stacked_subfigures_into_3x2_grid(figures):
    # HOW DO I DO THIS?
    pass

def stacked_lineplots():
    # Create a figure with two vertically stacked subplots
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
    
    # Dummy data for the plots
    x = [0, 1, 2, 3, 4]
    y1 = [0, 1, 4, 9, 16]
    y2 = [16, 9, 4, 1, 0]
    
    # Plot the data on the first subplot
    ax1.plot(x, y1, label='y = x^2')
    ax2.plot(x, y2, label='y = 16 - x^2', color='orange')
    
    # Adjust layout to prevent overlap
    plt.tight_layout()
    
    return fig

# To get the figure, simply call the function:
six_figures = []
for i in range(6):
    stacked_sub_figure = stacked_lineplots()
    six_figures.append(stacked_sub_figure)

# Now, you can arrange these figures into a 3x2 grid
grid_figure = arrange_stacked_subfigures_into_3x2_grid(six_figures)

print("Done")

示例堆叠子图:

enter image description here

所需的最终图: 3 列和 2 行堆叠对的网格。

enter image description here

python matplotlib figure
1个回答
0
投票

实现此目的的一种方法是使用

GridSpec
(对于主网格)和
GridSpecFromSubplotSpec
(对于每个单元格/子图):

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def stacked_lineplots():
    # Create a figure with a specific size
    fig = plt.figure(figsize=(15, 12))
    
    # Define an outer GridSpec with 3 rows and 2 columns for the pairs
    outer_gs = gridspec.GridSpec(2, 3, figure=fig, wspace=0.4, hspace=0.3)  
    
    # Dummy data for the plots
    x = [0, 1, 2, 3, 4]
    y1 = [0, 1, 4, 9, 16]
    y2 = [16, 9, 4, 1, 0]
    
    # Loop over each cell in the outer grid
    for col in range(3):  
        for row in range(2):  
            # Define inner GridSpec for the stacked pair within each outer cell
            inner_gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=outer_gs[row, col], hspace=0.2, wspace = 0.1)  
            
            # Top plot of the stacked pair
            ax1 = fig.add_subplot(inner_gs[0])
            ax1.plot(x, y1, label='y = x^2')
            ax1.legend()
            
            # Bottom plot of the stacked pair
            ax2 = fig.add_subplot(inner_gs[1])
            ax2.plot(x, y2, label='y = 16 - x^2', color='orange')
            ax2.legend()
    plt.show()

stacked_lineplots()

输出: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.