0

I have a dataframe which i had to transfer into numpy arrays, because i want to plot over the index which is a datetime but i get this error:

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"

Here is my dataframe:

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

this is the way i transfermed it np arrays in order to plot it

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

then im plotting it

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

works fine except for the legend i tried to use mlp's legend function and to create the legend manually therefore i altered my code:

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

which gives me the following error:

AttributeError: 'list' object has no attribute 'get_label'
user10395806
  • 85
  • 2
  • 11

1 Answers1

0

solved for the numpy array by calling

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

although i dont really understand it. found the answer here: Python legend attribute error

user10395806
  • 85
  • 2
  • 11