在使用 matplotlib 绘制文本时使用 %s,%f,...

Use of %s,%f,... when plotting text with matplotlib

我目前正在使用 matplotlib(实际上是 pylab)进行绘图,并希望执行以下操作:

  1. 声明一个变量,例如a=2.

  2. 在我的图表上打印一些文字:plt.text(x,y,r'an equation involving "a"')

我为绘制该方程所做的工作是编写 plt.text(x,y,r'x+3.5$')(这将使用 LaTeX)。然而,我不想自己写那个 2,而是想写类似 plt.text(x,y,r'$%fx+3.5$',a) 的东西。在这种情况下,"a" 作为参数传递,这是行不通的。

此外,如果 a 的类型是:numpy.float64 怎么办?

有没有办法实现我想要的?

您可以将字符串加在一起。

import matplotlib.pyplot as plt

ys = [x**2 + 3.5 for x in xrange(20)]
xs = range(20)
plt.plot(xs,ys)

a = '2'

plt.text(6, 50,r'$'+a+'x+3.5$')
plt.show()

如果 a 不是字符串,您可以将其设为一个! str(a)

或使用string formatting