【问题标题】:matplotlib shows no legend [duplicate]matplotlib 没有显示图例 [重复]
【发布时间】:2018-11-22 17:12:29
【问题描述】:

我有一个数据框,我必须将它转移到 numpy 数组中,因为我想在索引上绘制一个日期时间,但我得到了这个错误:

KeyError: "DatetimeIndex(['2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01',\n               '2004-01-01', '2005-01-01', '2006-01-01', '2007-01-01',\n               '2008-01-01', '2009-01-01', '2010-01-01', '2011-01-01',\n               '2012-01-01', '2013-01-01', '2014-01-01', '2015-01-01',\n               '2016-01-01', '2017-01-01'],\n              dtype='datetime64[ns]', name='year', freq=None) not in index"

这是我的数据框:

rel_uncertain   rel_modal_wk    rel_positive    rel_modal_me    rel_modal_st    rel_cnstrain    rel_litigious   rel_negative    year
0   0.003264    0.000568    0.007659    0.002442    0.011443    0.002170    0.004246    0.003857    2000-01-01
1   0.006195    0.002193    0.007991    0.002325    0.009876    0.002229    0.007343    0.006189    2001-01-01
2   0.005952    0.000719    0.011846    0.001773    0.009697    0.001392    0.001874    0.003313    2002-01-01
3   0.006306    0.001038    0.008452    0.001925    0.009386    0.001180    0.002856    0.001219    2003-01-01
4   0.005013    0.001374    0.007348    0.001017    0.008259    0.001533    0.003306    0.004437    2004-01-01

这是我为了绘制它而将它传输到 np 数组的方式

    year=np.array(df12.year)
un=np.array(df12.rel_uncertain,)
neg= np.array(df12.rel_negative)

然后我在绘制它

plt.plot(x,neg, label = 'neg')
plt.plot(x,pos,)

工作正常,除了图例 我尝试使用 mlp 的图例功能并手动创建图例 因此我改变了我的代码:

negative=plt.plot(x,neg,linestyle ='dashed', label='negative')
plt.plot(x,pos,)
plt.legend(handles=[negative])

这给了我以下错误:

AttributeError: 'list' object has no attribute 'get_label'

【问题讨论】:

  • 检查你传递的参数类型。
  • 你到底是什么意思?

标签: python python-3.x pandas matplotlib


【解决方案1】:

通过调用解决了numpy数组

negative=plt.plot(x,neg,linestyle ='dashed', label='negative')
positive= plt.plot(x,pos,label = 'positive')
plt.legend(handles=[negative[0],positive[0]])

虽然我不太明白。 在这里找到答案:Python legend attribute error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2015-06-15
    • 2018-12-27
    • 2023-01-18
    • 2015-08-05
    相关资源
    最近更新 更多