Question Details

No question body available.

Tags

python matplotlib label legend-properties

Answers (1)

Accepted Answer Available
Accepted Answer
June 5, 2026 Score: 3 Rep: 151,307 Quality: Expert Completeness: 100%

The simplest is to use label= only for one black line.

e.g. for last line - to have it as last element in legend.

if i == 9:
    plt.plot(x, Fit, "k-", label="Fit")
else:
    plt.plot(x, Fit, "k-")

Other method is to plot all black lines without labels

plt.plot(x, Fit, "k-")

and later add own element in legend

handles, labels = plt.gca().getlegendhandleslabels()

handles.append(plt.Line2D([0], [0], color="black")) labels.append("Fit")

plt.legend(handles, labels)


Result:

enter image description here


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1, 6, 10)

plt.figure()

for i in range(10): T = i + 20 Fit = 4 * x - (2 + i) noise = np.random.normal(loc=0, scale=1.0, size=len(Fit)) dataexp = Fit + noise / 5 plt.scatter(x, dataexp, marker="o", label=f"Experimental data T = {T}°C")

# plt.plot(x, Fit, "k-") # , label=f'Fit T = {T}°C') # if i == 9: # plt.plot(x, Fit, "k-", label=f"Fit") # else: # plt.plot(x, Fit, "k-")

plt.plot(x, Fit, "k-")

handles, labels = plt.gca().getlegendhandleslabels() handles.append(plt.Line2D([0], [0], color="black")) labels.append("Fit") plt.legend(handles, labels)

plt.xlabel("Optical power (mW)") plt.ylabel("Current (mA)") plt.grid(True) plt.show()


Matplotlib doc: