3

I have a set of nested dictionaries for which I'm generating subplots. I need to read and filter by the terminal answers in the dictionaries, then graph results based on variables along the dictionary tree. In some cases the variables along the tree are indexes used to slice other datasets:

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]...

I want to generate a separate subplot for each iteration of the complete loop, preferably arranged in a single column (I have other uses for other columns). If I knew the total number of instances I would get from the loop, then I could just use plt.subplots(rows, columns)and index each instance with axes[row,column].plot(...). When I try fig.add_subplot methods, I keep getting subplots that overlap each other in a nested fashion - the subplots don't update their locations to reflect a figure that grows with each loop iteration.

Maybe that's bad code practice, so I also have a version where I grab the total number of entries by just counting the number of 'yes' answers when iterating over the dictionaries, then using that number with the plt.subplots(rows,columns) strategy above. To do that I have to write that conditional nested loop and iterate over it a second time (once to get the total, then again to draw the subplots), but that also seems inefficient.

1 Answer 1

2

Sometimes writing out your question provides you with an answer. I'll write mine here in case any have commentary or have a similar question. When iterating through the nested dictionary, in addition to counting/collecting the terminal answers, I also collect the variables I'll need later for graphing, append them in lists.

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]]...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.