Error with using pandas.series.dt.year in adding a legend

Screen Link:
https://app.dataquest.io/m/143/multiple-plots/10/adding-a-legend

My Code:

fig = plt.figure(figsize=(10,6))
colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    plt.plot(subset['MONTH'],subset['VALUE'],c=colors[i],label=subset['DATE'].dt.year)
    
plt.legend(loc='upper left')
plt.show()

What I expected to happen: It need to label the year of each plotted line and show the in the “plt.legend(loc=‘upper left’)” , although i have correct my code using "label=1948+i ", but i wanted to know what is the problem with using pandas.series.dt.year at that place , why it is showing this error?

What actually happened: It show the error :-

AttributeErrorTraceback (most recent call last)
<ipython-input-1-5a300a27923f> in <module>()
      8 
      9 plt.legend(loc='upper left')
---> 10 plt.show()

/dataquest/system/env/python3/lib/python3.4/site-packages/matplotlib/pyplot.py in show(*args, **kw)
    242     """
    243     global _show
--> 244     return _show(*args, **kw)
    245 
    246 

/dataquest/system/libs/dq_matplotlib_backend.py in show(*args, **kw)
    119         figures = []
    120         for figure_manager in Gcf.get_all_fig_managers():
--> 121             figure_manager.canvas.draw()
    122             figures.append(figure_manager.canvas.figure)
    123 

/dataquest/system/libs/dq_matplotlib_backend.py in draw(self)
    191         record_hashes(
    192             figure_manager.canvas.get_renderer().image_hash()
--> 193             for figure_manager in Gcf.get_all_fig_managers()
    194         )
    195 

/dataquest/system/libs/dq_matplotlib_backend.py in record_hashes(hashes)
    305         os.path.join(os.path.sep, "dataquest", "results", "image-hashes.lst"), "a"
    306     ) as f:
--> 307         f.writelines(hash_ + "\n" for hash_ in hashes)
    308 
    309 

/dataquest/system/libs/dq_matplotlib_backend.py in <genexpr>(.0)
    305         os.path.join(os.path.sep, "dataquest", "results", "image-hashes.lst"), "a"
    306     ) as f:
--> 307         f.writelines(hash_ + "\n" for hash_ in hashes)
    308 
    309 

/dataquest/system/libs/dq_matplotlib_backend.py in <genexpr>(.0)
    191         record_hashes(
    192             figure_manager.canvas.get_renderer().image_hash()
--> 193             for figure_manager in Gcf.get_all_fig_managers()
    194         )
    195 

/dataquest/system/libs/dq_matplotlib_backend.py in image_hash(self)
     63 
     64     def image_hash(self):
---> 65         hash_ = image_hash(list(self._dq_log))
     66         self._dq_log.clear()
     67         return hash_

/dataquest/system/libs/dq_matplotlib_backend.py in image_hash(image_log)
    298 
    299 def image_hash(image_log):
--> 300     return "dq-image-{}".format(hashobj(normalize(image_log)))
    301 
    302 

/dataquest/system/libs/dq_matplotlib_backend.py in normalize(log)
    290 
    291 def normalize(log):
--> 292     return sorted({json.dumps(dict(Element(el)), sort_keys=True) for el in log})
    293 
    294 

/dataquest/system/libs/dq_matplotlib_backend.py in <setcomp>(.0)
    290 
    291 def normalize(log):
--> 292     return sorted({json.dumps(dict(Element(el)), sort_keys=True) for el in log})
    293 
    294 

/dataquest/system/libs/dq_matplotlib_backend.py in __iter__(self)
    224         for method in self.fields():
    225             try:
--> 226                 yield (method, getattr(self, method)())
    227             except KeyError:
    228                 pass

/dataquest/system/libs/dq_matplotlib_backend.py in text(self)
    256     def text(self):
    257         mtext = self._getfield("text")
--> 258         return str(mtext.get_text())
    259 
    260     def ismath(self):

AttributeError: 'NoneType' object has no attribute 'get_text'

Hi @nishu123tushar

In the label parameter which you have to set a value (name of the plot), but using subset['DATE'].dt.year returns a series object, and also all elements are same because you are plotting for each year. You can check its type using type() function.

For labeling the plot using series.dt.year attribute you can assign subset['DATE'].dt.year.iloc[0] to label parameter.

I hope this makes sense :slightly_smiling_face: .

1 Like