我目前使用下面的代码块解决了我的问题。它能够实现我的需求,但是有很多重复的代码,并且有些难以阅读。
我需要创建几个图表,并用在一个大的for循环中计算出的数据填充这些图表。
我遇到了困难,无法理解如何在代码的顶部创建并设置标题/元数据,然后在代码底部将所有正确的数据添加到相应的图表中。
我目前的代码如下:
import matplotlib.pyplot as plt
import numpy as np
figure = plt.figure()
plt.title("Figure 1")
figure.add_subplot(2,2,1)
plt.imshow(np.zeros((2,2)))
# Some logic in a for loop to add subplots
plt.show()
figure = plt.figure()
plt.title("Figure 2")
figure.add_subplot(2,2,1)
# Some Logic in an identical for loop to add different subplots
plt.imshow(np.zeros((2,2)))
plt.show()
我希望得到更像这样的东西:
我想要一个更加类似于这个的东西:
# Define variables, titles, formatting, etc.
figure = plt.figure()
figure2 = plt.figure()
figure1.title = "Figure 1"
figure2.title = "Figure 2"
# Populate
figure.add_subplot(2,2,1)
figure2.add_subplot(2,2,1)
# Some logic in a for loop to add subplots to both figures
有没有一种干净的方式可以使用Matplotlib完成我所要求的?我主要是想清理我的代码并拥有一个更易于扩展和维护的程序。
我真的只是想在一个地方定义所有的图形及其标题,然后根据一些其他逻辑将图像添加到正确的图形中。能够针对特定的图形调用plt.show()也很好。