Matplotlib returns duplicate legends when only ask to show one for each label

Viewed 20

I was trying to plot two regression lines on the same plot using matplotlib and the plot returned duplicate legends for the line labeled as: 'OLS regression line'. I could not figure out why. Could someone explain the possible reasons?

fig, ax = plt.subplots(figsize =(10,5))

ax.scatter(x, y)
ax.set_ylabel('y', fontsize=12)
ax.set_xlabel('x', fontsize=12)
ax.plot(x2, y_hat, '-g', label='OLS regression line')
ax.plot(x, y_, '-r', label='population regression line')


#show plots
plt.legend(loc='upper left')
plt.show()

This is the plot: Output Plot

Thank you.

1 Answers

 A simple interpretation of your question points to me that you need to display the data in text format, so you could omit label parameter and make use of text method:

rdn = np.random.default_rng(1234)

# generate data
x = rdn.uniform(0, 10, size=100)
y = x + rdn.normal(size=100)

fig, ax = plt.subplots(figsize =(10,5))

ax.scatter(x, y)

# simple linear regression 
b, a = np.polyfit(x, y, deg=1)

# Create sequence of 100 numbers from 0 to 100 
xseq = np.linspace(0, 10, num=100)

ax.set_ylabel('y', fontsize=12)
ax.set_xlabel('x', fontsize=12)
ax.plot(x2, y_hat, '-g', label='OLS regression line')
ax.plot(x, y_, '-r', label='population regression line')

# add text box for the statistics
stats = (f'OLS regression line\n'
         f'population regression line')
 
bbox = dict(boxstyle='round', fc='blanchedalmond', ec='orange', alpha=0.5)
ax.text(0.95, 0.07, stats, fontsize=9, bbox=bbox, transform=ax.transAxes, horizontalalignment='right')

plt.show()
Related