mr.graziani
mr.graziani

Reputation: 23

Matplotlib subplot legend in a loop

I have a loop in which I create a plot for each of the elements in the loop and a legend explaining the plot. When I try to save it I have all the plots but just the last legend created, like it is always overwriting it. Here's my code:

yearfig, yearaxis = plt.subplots(1, figsize=(15, 10))

  for year in np.range(2017, 2020):
      
      for pair in range(0, len(results)):

         stock1 = results.loc[pair][0]
         stock2 = results.loc[pair][1]
         value = stock1/stock2

         yearaxis.plot(results.index, value)
         yearaxis.legend([stock1+'-'+stock2])
       
      yearfig.savefig('test-'+str(year)+'.pdf')

What I expected was a single plot with all the lines and a legend with the name of the stocks in format "stock1-stock2" for each line. What I end up with is a plot with all the lines but a legend with only the last stocks (last line created).

I tried to explain it as best as I could. Does someone know how to solve that?

Upvotes: 0

Views: 138

Answers (1)

Tarifazo
Tarifazo

Reputation: 4343

You are overwriting the legend each time using the last value of stock1 and stock2. Try passing the legend using the label keyword, like this:

yearfig, yearaxis = plt.subplots(1, figsize=(15, 10))

  for year in np.range(2017, 2020):
      
      for pair in range(0, len(results)):

         stock1 = results.loc[pair][0]
         stock2 = results.loc[pair][1]
         value = stock1/stock2

         yearaxis.plot(results.index, value, label=stock1+'-'+stock2)
      yearaxis.legend(loc='best') #let matplotlib try to figure out where the legend should go
       
      yearfig.savefig('test-'+str(year)+'.pdf')

Upvotes: 1

Related Questions