通过带有matplotlib的python中的数组字典通过迭代进行子图

时间:2020-05-14 22:01:07

标签: python matplotlib data-science

我有一个数组字典(40个条目,每个数组的形状=(5001,)),我希望能够遍历并在5 * 8网格中创建子图。到目前为止,我只能解决如何制作40 * 1网格的问题:

fig, axes = plt.subplots(40,sharex=True,sharey=True,figsize=(3,30))
for i, (key, value) in enumerate(new_dict.items()):
    print(i, key, value)
    axes[i].plot(value)
    axes[i].set(title=key.upper(), xlabel='ns')
plt.show()

40*1 grid

像这样的事情会将最后一个图放在5 * 8网格的每个图中:

fig, axes = plt.subplots(ncols=5,nrows=8,sharex=True,sharey=True,figsize=(10,30))
axes = axes.flatten()
for i, ax in enumerate(axes.flatten()):
    for a, (key, value) in enumerate(new_dict.items()):
        print(a, key, value)
    ax.plot(value)
    ax.set(title=key.upper(), xlabel='ns')
plt.show()

Single (final) plot in each graph

并切换for循环会将所有图覆盖在5 * 8网格的每个图中:

fig, axes = plt.subplots(ncols=5,nrows=8,sharex=True,sharey=True,figsize=(10,30))
for i, ax in enumerate(axes.flatten()):
    for a, (key, value) in enumerate(new_dict.items()):   
        print(a, key, value)
        ax.plot(value)
        ax.set(title=key.upper(), xlabel='ns')
plt.show()

All plots in each graph

我一生无法解决如何在每个图中绘制不同的图。任何帮助将不胜感激!我觉得我在这里确实缺少一些明显的东西。非常感谢:-)

编辑:我已经意识到for循环的位置无关紧要,而ax.plot的制表符...会改变最后一个图填充图形还是所有图。

1 个答案:

答案 0 :(得分:0)

您可以创建具有指定大小的子图网格:

# sample data
new_dict = {str(i): np.linspace(0,1,100)**i for i in range(40)}

fig, axes = plt.subplots(5,8,sharex=True,sharey=True,figsize=(8,5))

#flatten axes so you can access axes[i]
axes = axes.ravel()

for i, (key, value) in enumerate(new_dict.items()):
    print(i, key, value)
    axes[i].plot(value)
    axes[i].set(title=key.upper(), xlabel='ns')
plt.show()

您会得到这样的东西:

enter image description here