Home > Software engineering >  Why legend in matplotlib only show one string?
Why legend in matplotlib only show one string?

Time:01-16

I am trying to loop legend in python. Here is my code.

for i in range(int(np.sqrt(n))):

    x=list(df_vrp.iloc[sol[i],1])

    y=list(df_vrp.iloc[sol[i],2])
    plt.plot(x,y)
    plt.legend("Truck" str(i 1),loc='upper left')

However, the result is like below. Why the legend can not loop and it only showed one letter?

enter image description here

CodePudding user response:

I think its because, plt.legend requires an iterable with the names, so why not try this...

legend=[]

for i in range(int(np.sqrt(n))):

    x=list(df_vrp.iloc[sol[i],1])

    y=list(df_vrp.iloc[sol[i],2])
    plt.plot(x,y)
    legend.append(f"Truck{i 1}")

plt.legend(legend,loc='upper left')
  •  Tags:  
  • Related