简体   繁体   中英

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()

K1的图表

K2的图表

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM