[Python] 6 subplot containing 2 subplots vertically aligned using Matplotlib

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Consider the single plot:

    import matplotlib.pyplot as plt
    import numpy as np

    # Generate sample data
    x = np.linspace(0, 10, 100)
    y1 = np.sin(x) # Data for the top subplot
    y2 = np.cos(x) # Data for the bottom subplot

    # Create the figure and two subplots, sharing the x-axis
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), sharex=True, gridspec_kw={"hspace": 0.4})

    # Plot data on the first subplot
    ax1.plot(x, y1, label="sin(x)", color="blue")
    ax1.set_ylabel("Top Y-Axis")
    ax1.set_title("Two Vertically Aligned Subplots")
    ax1.legend()

    # Plot data on the second subplot
    ax2.plot(x, y2, label="cos(x)", color="orange")
    ax2.set_ylabel("Bottom Y-Axis")
    ax2.set_xlabel("Shared X-Axis")
    ax2.legend()

    # Show the plot
    plt.show()



    I'd like to have 6 of these curves (2x3) within a single plot, such that:

    fig, axs = plt.subplots(2, 3, figsize=(16, 8), tight_layout=True)


    In other words, I'd like to set 6 figures, each containing 2 subplots vertically aligned each. Is that possible using matplotlib?

    The example code is available.

    Continue reading...

Compartilhe esta Página