【问题标题】:Iteratively adding subplots in matplotlib with unknown total number在 matplotlib 中迭代地添加子图,总数未知
【发布时间】:2018-10-08 19:28:40
【问题描述】:

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

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) 策略一起使用.为此,我必须编写条件嵌套循环并对其进行第二次迭代(一次获取总数,然后再次绘制子图),但这似乎也效率低下。

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    有时写下您的问题可以为您提供答案。如果有人有评论或有类似问题,我会在这里写下我的。遍历嵌套字典时,除了计数/收集终端 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]]...
    

    【讨论】:

      猜你喜欢
      • 2019-07-13
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2017-07-20
      • 2016-04-28
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多