0

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?

1
  • 1
    Here you are trying to give the label twice, cant you append the value into a single string and then assign it to the label Commented Dec 16, 2016 at 19:15

1 Answer 1

1

'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)

Sign up to request clarification or add additional context in comments.

1 Comment

is it also possible to change the number of decimal places of t[0] within that format function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.