JDGD JDGD - 22 days ago 17
Python Question

Label objects not found

Setup a graph using matplotlib which is working properly (see image below), but when I try to add a legend I get the following error:

UserWarning: No labeled objects found. Use label='...' kwarg on indivial plots.


Here's the code I'm using to define the lines that I want in the legend and draw the legend:

#Moving average labels
smaLabel1 = str(SMA1)+'d SMA'
smaLabel2 = str(SMA2)+'d SMA'
smaLabel3 = str(SMA3)+'d SMA'

#Add SMAs to chart
ax1.plot(ind, avg1, '#5998ff', label=smaLabel1, linewidth=1)
ax1.plot(ind, avg2, '#ffbb82', label=smaLabel2, linewidth=1)
ax1.plot(ind, avg3, '#d689c4', label=smaLabel3, linewidth=1)
""" End SMA additions """

#Add legend
plt.legend()


I've checked the
smaLabel
variables, and all hold the correct strings. Anyone know why the labels aren't registering?

enter image description here

Answer

You must have plot the candle plots and the volume before plotting the SMA. The candle plot doesn't have any labeled object, when you call the plt.legend(), it tries to plot a label for every plot on the current axes. Therefore, you get this UserWarning: No labeled objects found. Use label='...' kwarg on indivial plots.

To solve it, I hope it is clear at this point, simply requires you to plot the SMA's very first, before the candle plot, and call the legend() right after that before any other plots being generated.

Comments