【问题标题】:Matplotlib subplot legend in a loop循环中的 Matplotlib 子图图例
【发布时间】:2021-08-20 16:52:00
【问题描述】:

我有一个循环,我在其中为循环中的每个元素创建了一个图,以及一个解释该图的图例。当我尝试保存它时,我拥有所有的情节,但只创建了最后一个图例,就像它总是覆盖它一样。这是我的代码:

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')

我所期望的是一个包含所有行的图和一个图例,其中每行的股票名称格式为“stock1-stock2”。我最终得到的是一个包含所有线条的情节,但只有最后一个股票(创建的最后一行)的图例。

我尽力解释它。有人知道如何解决吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您每次都使用stock1stock2 的最后一个值覆盖图例。尝试使用 label 关键字传递图例,如下所示:

    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')
    

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 2015-08-18
      • 2013-09-24
      • 2015-10-10
      • 2011-11-03
      • 2020-07-23
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多