No handles with labels found to put in legend warning occurs in Matplotlib when we call legend() function without labels and their respective handles while plotting visualizations. In this article we will understand the root cause for this warning and also explore how can we fix this warning.
No handles with labels found to put in legend ( Cause ) –
Lets draw any simple matplotlib chart and understand –
import matplotlib.pyplot as plt import numpy as np x = np.array(["Div1", "Div2", "Div3", "Div4"]) y = np.array([30, 18, 21, 28]) plt.bar(x,y) plt.legend() plt.show()
Here plt.legend() is called without any handle and their respective labels. Hence we will get the same warning (No handles with labels found ). Lets see the output-
matplotlib.pyplot.legend() is for adding legends on plot.
Solution 1 : passing legend name as parameter
The simplest and easiest way to fix this warning is providing the legend name with parameter.
Solution 2 : Passing Labels with Autodetect in legend() function-
Here we will provide the label while plotting bar chart and when we call
plt.bar(x,y ,label='Points as Label')
Lets understand how ?
Multi Label Legend with parameters-
Multiple Labels with multiple handler –
So far we have considered the single bar chart. Now we will see how can legend works in multiple visualization. As we were calling simply legend function , here we will provide handlers and labels in list format to them. Here handlers are necessary because without it it will be difficult to recognize the labels for each plot.
Here is the simple example to understand the concept.
import matplotlib.pyplot as plt import numpy as np x = np.array(["Div1", "Div2", "Div3", "Div4"]) y1 = np.array([30, 18, 21, 28]) y2 = np.array([40, 32, 29, 11]) X_axis = np.arange(len(x)) day_team_bar=plt.bar(X_axis - 0.2,y1,0.4) night_team_bar=plt.bar(X_axis + 0.2,y2,0.4) plt.xticks(X_axis, x) plt.legend(handles = [day_team_bar, night_team_bar], labels = ['Day', 'Night']) plt.show()
Lets see the output-
Passing Legends parameter with Labels without handler –
In the above visualization we passed two argument in the legend() function. But we do not pass respective handler , it will work on position basis.
Multi Label Legend without parameters ( Auto Detect )-
As we have seen in the single label legend that we can declare the same without parameter too. While plotting we can set the labels and legend function will auto detect the same at run time and we will not get this warning – No handles with labels found to put in legend in Matplotlib .
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.