python - 在 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)
上面的策略使用该数字。为此,我必须编写条件嵌套循环并对其进行第二次迭代(一次获取总数,然后再次绘制子图),但这似乎也效率低下。
解决方案
有时写下你的问题会给你一个答案。如果有人有评论或有类似问题,我会在这里写下我的。遍历嵌套字典时,除了计数/收集终端之外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]]...
推荐阅读
- mysql - 当我在 SELECT 中定义它时,为什么 MySQL 会给我“错误代码:1054。'on 子句'中的未知列 'x'”?
- azure - 无法看到要注册的 Azure Microsoft.classiccompute 提供程序
- design-patterns - 用于演示的高内聚和松散耦合的真实示例
- javascript - 如何根据另一个对象数组的值创建一个对象数组?
- android - Android dagger 2:没有@Provides-annotated 方法就无法提供依赖项
- groovy - 循环遍历类成员并在groovy中更新成员值
- java - 为暂存文件创建缺少的类意图
- python - 如何通过电子邮件将保存的 Blob 作为附件发送?
- c++ - g++ 在使用“-Wno-deprecated”时不会忽略“deprecated-declaration”+“Werror”错误
- javascript - 工具栏的Webkit动画