Skip to content
Advertisement

How to loop through lists to create multiple plots Python

I have the following three lists:

list 1: ['Dog','Cat','Mouse']
list 2: [['3','8','9'],['6','7','8'],['3','8','9']]
list 3: [['11:03:15','11:05:15',11:08:15'],['11:03:15','11:05:15',11:08:15'],['11:03:15','11:05:15',11:08:15']]

I was wondering how I can take these 3 lists and iterate through them to get lists

so the first plot would be plotting dog as title with y value as the first list in 2d list 2 and the x value would the first list in 2d list 3. This would iterate for each value.

My idea is I think to zip these 3 lists like result = zip(list1,list2,list3)

and then somehow iterate to do something like this but Python says zip object is not subscriptable

for i,j,k in range(1, 60):
    df.plot(kind = 'line',x=list1[i], y=list2[j], ax = ax, label =list3[k], figsize=(16,8))

Could anyone explain how I can do this??

Advertisement

Answer

It seems to me that you want something fairly straightforward:

import matplotlib.pyplot as plt 

list1 = ['Dog', 'Cat', 'Mouse']
list2 = [['3', '8','9'],
         ['6', '7', '8'],
         ['3', '8', '9']]
list3 = [['11:03:15', '11:05:15', '11:08:15'],
         ['11:03:15', '11:05:15', '11:08:15'],
         ['11:03:15', '11:05:15', '11:08:15']]

for title, y, x in zip(list1, list2, list3):
    fig, ax = plt.subplots() # Create a new figure.
    ax.set_title(title)      # Set the title to dog/cat/mouse.
    ax.plot(x, y)            # Plot the data.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement