简体   繁体   English

如何使用 Matplotlib 在 Python 中创建垂直子图?

[英]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.我在 python 中有 2 个图,当按照代码的前两部分分别绘制它们时,它正确显示了前 2 个图。 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?但是,当尝试将 2 个图的子图制作成彼此下方的子图时,下图由 python 渲染。我在这里做错了什么?

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() . plt.subplot() function 需要位于imshow()之上。 Also, there is no need for clf() which is used only when you want to clear the current figure.此外,不需要clf() ,它仅在您要清除当前图形时使用。

OPTION 1 (State-based):选项 1 (基于状态):

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):选项 2 (面向对象):

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: output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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