Search code examples
pythonmatplotlibsubplot

How to create vertical subplot in Python using Matplotlib?


I have 2 plots in python and when plotting them separately as done in the first 2 sections of codes, it correctly displays the first 2 graphs. However, when trying to make a subplot of the 2 graphs beneath each other, the following picture is rendered by python. What am I doing wrong here?

K1 = 1
K2 = [[0. 0. 0.]
      [0. 3. 0.]
      [0. 0. 0.]]
# visualizing the source function
plt.clf()
plt.imshow([[K1, K1],
            [K1, K1]], cmap='viridis')
plt.colorbar()
plt.show()

plt.clf()
plt.imshow(K2, cmap='viridis')
plt.colorbar()
plt.show()

# visualizing the source function
plt.clf()
plt.imshow([[K1, K1],
            [K1, K1]], cmap='viridis')
plt.colorbar()
plt.subplot(2, 1, 1)


plt.clf()
plt.imshow(K2, cmap='viridis')
plt.colorbar()
plt.subplot(2, 1, 2)
plt.show()

graph of K1

graph of K2


Solution

  • The plt.subplot() function needs to be on top of imshow(). Also, there is no need for clf() which is used only when you want to clear the current figure.

    OPTION 1 (State-based):

    plt.figure(figsize=(10, 10))
    plt.subplot(2, 1, 2)
    plt.imshow([[K1, K1],
                [K1, K1]], cmap='viridis')
    plt.colorbar()
    plt.subplot(2, 1, 1)
    plt.imshow(K2, cmap='viridis')
    plt.colorbar()
    plt.show()
    

    OPTION 2 (OOP):

    fig, ax = plt.subplots(2, 1, figsize=(10, 10))
    sub_1 = ax[0].imshow([[K1, K1],
                          [K1, K1]], cmap='viridis')
    fig.colorbar(sub_1, ax=ax[0])
    sub_2 = ax[1].imshow(K2, cmap='viridis')
    fig.colorbar(sub_2, ax=ax[1])
    plt.show()
    

    output:

    enter image description here