首页 > 解决方案 > 多个 matplotlib 数字

问题描述

我在我的代码中使用 6 个不同的数字。我像这样初始化它们:

fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
fig3, ax3 = plt.subplots()
fig4, ax4 = plt.subplots()
fig5, ax5 = plt.subplots()
fig6, ax6 = plt.subplots()

此外,我使用轴和图形对象来绘制图形并保存它们。虽然代码工作得很好,但我想知道是否有更好的方法来处理这种情况(一种更优雅的方法)。是否有可用的图形/轴对象集合之类的东西?

如果确实存在这样的集合,那么在设置轴标签时会很轻松。可以循环遍历集合对象和我准备的标签列表,而不是单独定义每个轴标签。任何有关此事的线索将不胜感激。提前致谢。

标签: pythonmatplotlib

解决方案


创建多个图形和轴并设置一些属性的一种非常紧凑的方法是

import matplotlib.pyplot as plt

figs, axs = zip(*[plt.subplots() for _ in range(6)])
plt.setp(axs, xlabel="My X Label")
plt.show()

这将分别创建图形和轴的两个可迭代对象,并设置xlabel所有轴的。


推荐阅读