【问题标题】:pyplot legend not matching linespyplot图例不匹配行
【发布时间】:2014-09-02 16:14:32
【问题描述】:

我的图例与线条颜色不匹配。知道我如何解决这个问题以及我做错了什么吗?该代码从 yahoo Finance 下载数据,因此您应该能够在您的机器上按原样运行它并自己查看数据。感谢您的帮助!

import pandas.io.data as web
import datetime
import pandas as pd
import matplotlib.pyplot as plt

start = '5/1/2007'
end = '10/1/2007'
event = datetime.date(2007,6,27)
companies = ['AAPL','MSFT','BBRY','IBM']

all_data = {}
for ticker in companies:
        all_data[ticker] = web.get_data_yahoo(ticker, start,end)

price = pd.DataFrame({tic:data['Adj Close']
                    for tic, data in all_data.iteritems()})

volume = pd.DataFrame({tic:data['Volume']
                    for tic, data in all_data.iteritems()})

rels = price/price.ix[event]
plt.figure(figsize=(15,5))
for i in companies:
   plt.plot(rels.index,rels[i],label=i,lw=4.0)  
plt.legend(companies,loc='upper left')
plt.axvline(x=event)
plt.grid(True)
plt.show()

编辑:我注意到图例正在拾取 axvline,所以我将它移到图例之后,并按照 cmets 中的建议通过循环生成单独的绘图语句,但看起来这些行与中的正确名称不匹配传说。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我无法运行您的代码,因为我没有 pandas,但我总是在 plot 中使用 label。这可能需要您执行以下操作(重构):

    for i in _list_of_lines_you_want_to_plot:
       plt.plot(xs_for_this_line,ys_for_this_line,label=YOURLABELHERE)  
    plt.legend(loc='upper left')
    plt.grid(True)
    plt.show()
    

    至于为什么会发生这种情况,很难从代码中判断出来,但这可能与字典访问在程序的每次运行时都会改变这一事实有关,所以在绘制来自的键时尝试使用sorted一本字典,但这可能是错误的,我真的不知道。

    【讨论】:

    • 我试过了,我在图例中得到了不同的颜色,但它们仍然与线条颜色不匹配。不过谢谢你,它仍然会派上用场!
    【解决方案2】:

    您已通过调用plt.plot 标记了您的线路,因此您无需在调用plt.legend 时传递另一负载标签。换句话说替换

    plt.legend(companies,loc='upper left')
    

    plt.legend(loc='upper left')
    

    一切都会正常的。

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多