简体   繁体   English

Matplotlib中的多个标签

[英]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". 我已经创建了一个绘图,我希望绘图的第一个项目的标签部分为字符串,部分为数组“ t”的元素0。 I tried setting the variable the_initial_state equal to a string: 我尝试将变量the_initial_state设置为字符串:

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? 有什么办法可以让标签包含一个字符串和一个数组元素,并固定到小数位数?

'the initial state' already is a string, so you do not need to cast it again. 'the initial state'已经是一个字符串,因此您无需再次强制转换。

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 eg be done using the format function. 例如,可以使用format函数在python中包含字符串和浮点数。

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 例如,要将浮点数2.345672为2个小数位,请使用
"{:.2f}".format(2.345672)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM