matplotlib 如何在调用plt.show后重新显示子情节图

xt0899hw  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(107)

我正在使用jupyter notebook,我在for循环中使用matplotlib.pyplot.subplot()。在for循环的同一个单元格中,我调用plt.show()来显示图形。但是,它们太小了,所以我希望在另一个notebook单元格上重新绘制它们,而不必重复循环,这很耗时。
所以基本上我运行了一个代码,看起来像这样:

import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(5,1)
for ii in range(5):
    #some time consuming operations
    axs[ii].plot(np.random.randn(10))
plt.show()

由于所有的信息都包含在figaxs中,我假设我不必重复循环,而只是告诉matplotlib再次显示其信息应该已经在axs变量中的图。

6kkfgxo0

6kkfgxo01#

您可以从原始的Figure和Axes中 * 提取 * matplotlib艺术家,并使用Matplotlib的oop功能创建新的Figures和Axes。
这个mre创建一个新的图和轴;从 * 原始 * 轴的每个Line 2D获取x和y数据,并使用它来绘制新的轴。

fig, ax = plt.subplots()  # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])  # Plot some data on the axes.
ax.plot([1, 2, 3, 4], [2,4,6,8])  # Plot some data on the axes.
plt.show()

fig1,ax1 = plt.subplots()
for line in ax.get_lines():
    x,y = line.get_data()
    ax1.plot(x,y)
fig1.show()

其信息应该已经在axs变量中
这些对象中确实有很多东西。看看里面有什么是信息丰富的。尝试:

>>> from pprint import pprint
>>> pprint(fig.properties())

>>> pprint(ax.properties())

>>> for line in ax.get_lines():
...     pprint(line.properties())

我建议使用Matplotlib Tutorials,有时使用OOP功能是真正微调绘图的最佳/最简单的方法。即使在此之后,您也需要查阅Artists的文档以查找特定的方法和属性。
图形解剖

相关问题