Home > Blockchain >  Duplication of label in matplotlib legend
Duplication of label in matplotlib legend

Time:03-17

I used a for loop to plot two lines in a graph.

plt.figure(num=2, dpi=120)
plt.title(r"Fonction $\mu$(x) et sa spline cubique pour différents degrés")
plt.plot(xe_array, fu(xe_array), color="green", label=r"$\mu$(x)")

nlist=[50,200]
color_list=["red", "blue"]
for j in range(len(nlist)):
    x_=np.linspace(start=0, stop=1, num=nlist[j] 1)
    y_=np.array(fu(x_))
    ye_=csi.spline_cub(x_,y_, xe_array)[0]
    plt.plot(x_,y_,ye_, color=color_list[j], label=f"n={nlist[j]}")

plt.xlabel("x")
plt.ylabel("f(x)")
plt.ylim(-2,2)
plt.legend(loc=(1.04,0.5))
plt.show()

xe_array is already defined and is a linspace array.

This is the output: enter image description here

Is this a bug?

CodePudding user response:

You're plotting two lines in the same call of plt.plot function. It is plotting both x_, y_ and ye_.

I can not run your code since it's not complete, but here is something similar:

import matplotlib.pyplot as plt
import numpy as np

plt.figure(num=2, dpi=120)
plt.title(r"Fonction $\mu$(x) et sa spline cubique pour différents degrés")

x_=np.linspace(start=0, stop=1, num=50 1)
y_=np.array(np.sin(x_))
    
plt.plot(x_,y_,y_, color='r', label=f"n=50")

plt.legend(loc=(1.04,0.5))
plt.show()

And it produce two same legends.

The following produces one.

plt.plot(x_,y_, color='r', label=f"n=50")

Extra bit: I don't think this part is well-documented in the official doc. But my understanding is, this is "intentionally" very similar to the plot function in matlab. So that the following plots n lines with the same label:

plot(x1, y1, x2, y2, ... xn, yn, label='something')

In your case you only provided odd number of positional args, so I think it interpreted your last arg (ye_) as a y-only line. Hard to say this is a bug or a feature.

  • Related