Matplotlib图例重复问题:如何移除重复的拟合方程图例?
Hey there! Let's troubleshoot that duplicate fit equation in your Matplotlib legend and get it fixed up.
Common Reasons for Duplicate Legend Entries
First, let's break down why this might be happening:
- Duplicate label assignments: You might have accidentally added the same
labelparameter to your fit line plot twice (e.g., callingplt.plot()with the same fit equation label two times). - Redundant legend calls: If you're calling
plt.legend()multiple times without clearing previous entries, or if your fit logic is running in a loop that repeats the label addition. - Unintended duplicate plot elements: Maybe you're generating the fit line twice and assigning the same label each time without realizing it.
Fixes to Try
Here are concrete solutions to resolve this:
1. Remove Duplicate Label Assignments
First, scan your code for repeated plt.plot() calls for the fit line with identical labels. For example, if you have code like this:
# 🔴 This causes duplicates! plt.plot(x_fit, y_fit, label=f"y = {slope:.2f}x + {intercept:.2f}") plt.plot(x_fit, y_fit, label=f"y = {slope:.2f}x + {intercept:.2f}")
Delete one of the duplicate lines, so you only plot the fit line once with the label.
2. Manually Control Legend Entries
If you want full control over what appears in the legend, explicitly pass only the elements you want to keep. This avoids any accidental duplicates:
# Plot fit line without setting a label fit_line, = plt.plot(x_fit, y_fit) # Create legend with only the fit equation once plt.legend([fit_line], [f"Fit: y = {slope:.2f}x + {intercept:.2f}"])
Note the comma after fit_line—this unpacks the Line2D object from the tuple returned by plt.plot().
3. Deduplicate Existing Legend Entries
If you have other plot elements and don't want to rewrite all your code, you can fetch existing legend handles and labels, then remove duplicates before rendering the legend:
# Get current handles and labels handles, labels = plt.gca().get_legend_handles_labels() # Keep only the first occurrence of each label unique_entries = dict(zip(labels, handles)) # Update the legend with deduplicated entries plt.legend(unique_entries.values(), unique_entries.keys())
This method automatically filters out any duplicate labels, keeping only the first instance of each.
Working Example
Here's a clean, duplicate-free code snippet to reference:
import matplotlib.pyplot as plt import numpy as np # Sample data x = np.array([1, 2, 3, 4, 5]) y = np.array([2.1, 4.0, 5.2, 6.8, 8.1]) # Perform linear fit slope, intercept = np.polyfit(x, y, 1) x_fit = np.linspace(x.min(), x.max(), 100) y_fit = slope * x_fit + intercept # Plot data and fit line (only one label for the fit!) plt.scatter(x, y, label="Raw Data") plt.plot(x_fit, y_fit, label=f"Linear Fit: y = {slope:.2f}x + {intercept:.2f}") # Single legend call plt.xlabel("X") plt.ylabel("Y") plt.legend() plt.show()
This will render a legend with only one instance of your fit equation, no duplicates in sight!
内容的提问来源于stack exchange,提问作者Nora_F

