XBB
XBB

Reputation: 109

Multiple labels in Matplotlib

I've created a plot and I want the first item that I plot to have a label that is partly a string and partly element 0 of array "t". I tried setting the variable the_initial_state equal to a string:

the_initial_state = str('the initial state')

And the plotting as follows:

plt.figure(5) 
fig = plt.figure(figsize=(6,6), dpi=1000)
plt.rc("font", size=10)
plt.title("Time-Dependent Probability Density Function")  
plt.xlabel("x")
plt.xlim(-10,10)
plt.ylim(0,0.8)
plt.plot(x,U,'k--')
**plt.plot(x,Pd[0],'r',label= the_initial_state, label =t[0])** 
plt.plot(x,Pd[1],'m',label=t[1])
plt.plot(x,Pd[50],'g',label=t[50])
plt.plot(x,Pd[100],'c',label=t[100])
plt.legend(title = "time", bbox_to_anchor=(1.05, 0.9), loc=2, borderaxespad=0.)

But I receive an "invalid syntax" error for the line that is indicated by ** **.

Is there any way to have a label that contains a string and an element of an array to a fixed number of decimal places?

Upvotes: 0

Views: 1884

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339660

'the initial state' already is a string, so you do not need to cast it again.

I do not see a syntax error for the moment, but surely you cannot set the label twice.

Concattenating a string and a float in python can e.g. be done using the format function.

the_initial_state = 'the initial state {}'.format(t[0])
plt.plot(x,Pd[0],'r',label= the_initial_state) 

should work.

There is a nice page outside explaining the format syntax. For example, to format the float 2.345672 to 2 decimal places, use
"{:.2f}".format(2.345672)

Upvotes: 1

Related Questions