首页 > 解决方案 > 在 matplotlib 中迭代地添加子图,总数未知

问题描述

我有一组嵌套字典,我正在为其生成子图。我需要通过字典中的终端答案阅读和过滤,然后根据字典树中的变量绘制结果。在某些情况下,树中的变量是用于切片其他数据集的索引:

for field in data.keys():
    if field.startswith('Header'):
        for subheading in data.get(field):
            for index, answer in data.get(field).get(subheading).get('Directory').items():
                if answer=='yes':
                   axes.plot(index, seconddataset[subheading]...

我想为完整循环的每次迭代生成一个单独的子图,最好安排在一个列中(我对其他列还有其他用途)。如果我知道从循环中获得的实例总数,那么我可以使用plt.subplots(rows, columns)每个实例并使用axes[row,column].plot(...). 当我尝试fig.add_subplot方法时,我不断得到以嵌套方式相互重叠的子图 - 子图不会更新它们的位置以反映随着每次循环迭代而增长的图形。

也许这是不好的代码实践,所以我还有一个版本,我通过'yes'在迭代字典时仅计算答案的数量来获取条目总数,然后使用plt.subplots(rows,columns)上面的策略使用该数字。为此,我必须编写条件嵌套循环并对其进行第二次迭代(一次获取总数,然后再次绘制子图),但这似乎也效率低下。

标签: pythonmatplotlibsubplot

解决方案


有时写下你的问题会给你一个答案。如果有人有评论或有类似问题,我会在这里写下我的。遍历嵌套字典时,除了计数/收集终端之外answers,我还收集稍后用于绘图的变量,将它们附加到列表中。

for field in data.keys():
    if field.startswith('Header'):
        for subheading in data.get(field):
            for index, answer in data.get(field).get(subheading).get('Directory').items():
                if answer=='yes':
                    subheading_list.append(subheading)
                    index_list.append(index)

fig,axes = plt.subplots(len(index_list),3)
for i in range (0,len(index_list)):
    axes[i,0].plot(index_list[i], seconddataset[subheading_list[i]]...

推荐阅读