在 Python 中添加输入变量以绘制标题/图例

dze*_*kob 3 python text matplotlib legend

我想在绘图标题/图例/带注释的文本中显示用于绘制某个函数的参数的当前值。作为一个简单的例子,让我们以一条直线为例:

import numpy
import matplotlib.pyplot as plt

def line(m,c):
   x = numpy.linspace(0,1)
   y = m*x+c
   plt.plot(x,y)
   plt.text(0.1, 2.8, "The gradient is" *the current m-value should go here*)
   plt.show()

print line(1.0, 2.0)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我希望我的文字显示“渐变为 1.0”,但我不确定语法是什么。此外,我将如何包含下面的第二个(和更多)参数,以便它读取:

"梯度为1.0

截距为 2.0。”

N C*_*han 5

使用字符串格式化的.format()方法:

plt.text(0.1, 2.8, "The gradient is {}, the intercept is {}".format(m, c))
Run Code Online (Sandbox Code Playgroud)

在哪里mc你想要替换的变量。

如果在字符串前面加上whcih 表示格式化的字符串文字,则可以直接在Python 3.6+ 中编写这样的变量f

f"the gradient is {m}, the intercept is {c}"
Run Code Online (Sandbox Code Playgroud)