0

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

JayPeerachai
3,8523 gold badges18 silver badges34 bronze badges
asked Dec 5, 2022 at 17:32

1 Answer 1

2

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

answered Dec 5, 2022 at 17:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.