Many times while using matplotlib to visualize the data, we encounter this error and end up spending our precious time resolving this simple error.
We will be seeing what caused this error and how to come out of this situation quickly.
What does “No handles with labels found to put in legend” mean?
The ‘legend()’ function in Matplotlib, a popular data visualization library in Python, produces the error message “No handles with labels found to put in legend.”. It means that the ‘legend()’ function is unable to find any elements in the plot that have a label attribute, which it uses to create the legend.
Earlier, the error message used to look as shown in the image.
The recent update changed the error message to show the following error.
Some ways by which “No handles with labels found to put in legend” can occur
Here are some ways in which the “No handles with labels found to put in legend” error can occur in Python, along with example code for each case:
Using legend() before adding labels to the elements
You are trying to create a legend for a plot, but you haven’t added any elements to the plot with a label attribute. To fix this, you need to ensure that you have added at least one element to the plot with a label. For example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Plot some data without specifying a label
ax.plot([1, 2, 3], [10, 20, 30])
# Try to add a legend
ax.legend()
# Show the plot
plt.show()
To fix this error, you can use the ‘label’ parameter of the ‘plot’ function to specify the label for the line:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Plot some data and specify a label for the line
ax.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Add a legend
ax.legend()
# Show the plot
plt.show()
Calling legend() for a plot other than the one which we have labeled
You have added elements to the plot that have a ‘label’ attribute, but the ‘legend’ function is unable to find them because they are not part of the same ‘Axes’ object. To fix this, you need to make sure that you are using the correct ‘Axes’ object when calling the ‘legend’ function.
import matplotlib.pyplot as plt
# Create a figure with two Axes objects
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
# Plotting data on the first Axes and declaring a label
ax1.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Try to add a legend to the second Axes
ax2.legend()
# Show the plot
plt.show()
To fix this error, you can call the ‘legend()’ function on the correct ‘Axes’ object:
import matplotlib.pyplot as plt
# Create a figure with two Axes objects
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
# Plotting data on the first Axes and declaring a label
ax1.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Add a legend to the first Axes
ax1.legend()
# Show the plot
plt.show()
legend() can’t find because elements are not visible
You have added elements to the plot that have a ‘label’ attribute, but the ‘legend()’ function is unable to find them because they are not visible. This happens when we set the ‘visible’ attribute of the element to ‘False’. To fix this, set the elements you want to include in the legend to be visible.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Plot some data and specify a label
line, = ax.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Make the line invisible
line.set_visible(False)
# Try to add a legend
ax.legend()
# Show the plot
plt.show()
Set line.set_visible() as ‘True’ to fix it.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Plot some data and specify a label
line, = ax.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Make the line invisible
line.set_visible(True)
# Try to add a legend
ax.legend()
# Show the plot
plt.show()
Used legend() before describing the plot
Making the plot after the legend can also result in an error.
import matplotlib.pyplot as plt
# Create a figure and an Axes object
fig, ax = plt.subplots()
ax.legend()
# Plot some data and specify a label for the line
ax.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Show the plot
plt.show()
Simply put, the legend() function after the plot() function to get rid of this error.
import matplotlib.pyplot as plt
# Create a figure and an Axes object
fig, ax = plt.subplots()
# Plot some data and specify a label for the line
ax.plot([1, 2, 3], [10, 20, 30], label="Line 1")
# Shows legend
ax.legend()
# Show the plot
plt.show()
“No handles with labels found to put in legend” while working with pandas dataframe
This error typically occurs when there are no labeled elements in the plot to include in the legend.
This can happen for several reasons. For example, you may have forgotten to specify a label for each element in the plot, or you may have accidentally set the label to an empty string or ‘None’.
To fix this error, you need to make sure that the elements you want to include in the legend are set to be visible and have a valid label.
Here is an example of how to use it without getting into any errors:
import matplotlib.pyplot as plt
import pandas as pd
# Load data into a DataFrame
df = pd.read_csv("data.csv")
# Create a scatter plot
df.plot(kind="scatter", x="X", y="Y", label="Data")
# Add a legend
plt.legend()
# Show the plot
plt.show()
n this example, we are creating a scatter plot of two columns in a DataFrame, X
and Y
, and specify a label for the data points using the label
parameter. The legend()
function is then used to create a legend for the plot, and the show()
function displays the plot.
“No handles with labels found to put in legend” with geopandas
These types of errors have similar origins. We would have either forgotten to put a label to the element, or we would have used legend() for a different plot than we should have used, etc. To resolve we should see one example of how to use these libraries so as not to get any errors.
import matplotlib.pyplot as plt
import geopandas as gpd
# Load data into a GeoDataFrame
gdf = gpd.read_file("data.shp")
# Create a map
ax = gdf.plot(color="red", label="Data")
# Add a legend
ax.legend()
# Show the map
plt.show()
In this example, we are loading geospatial data from a shapefile into a GeoDataFrame and creating a map using the ‘plot()’ function. The ‘label’ parameter is used to specify a label for the data. The ‘legend()’ function is then used to create a legend for the map, and the ‘show()’ function displays the map.
What if the error occurs with seaborn?
The error message “No handles with labels found to put in legend” can also occur when using the legend()
function with a plot created using Seaborn, a Python data visualization library.
Again, we should just know a sample about how to use it with seaborn so as to thwart any mishappenings.
import matplotlib.pyplot as plt
import seaborn as sns
# Load data into a DataFrame
df = sns.load_dataset("tips")
# Create a scatter plot
sns.scatterplot(x="total_bill", y="tip", hue="time", data=df)
# Add a legend
plt.legend()
# Show the plot
plt.show()
In this example, we are loading the ‘tips’ dataset from Seaborn and creating a scatter plot using the ‘scatterplot()’ function. The ‘hue’ parameter is used to specify a label for the data points. The ‘legend()’ function is then used to create a legend for the plot, and the ‘show()’ function displays the plot.
What is the label attribute?
The ‘label’ attribute is an optional parameter of the ‘plot()’ function in the python library Matplotlib. It is used to specify a label for a line or scatter plot.
The ‘label’ attribute is used to create a legend for a plot.
What is the legend() function?
A legend is an area that describes the components of the graph. In Matplotlib, we use ‘legend()’ function to place a legend on the Axes. The ‘label’ attribute specifies the label for each element included in the legend.
FAQs
Matplotlib is used to visualize data in Python.
A scatter plot is a type of data visualization that uses dots to represent values for two different numeric variables. Each dot in a scatter plot represents a single data point, and the dot’s position on the x-axis and y-axis corresponds to the values of the two variables.