添加输入变量以在Python中绘制标题/传奇 [英] Adding input variables to plot title/legend in Python
问题描述
我想在绘图标题/图例/注释文本中显示用于绘图特定功能的参数的当前值.作为一个简单的例子,让我们走一条直线:
I would like to display the current value of a parameter used to plot a certain function in the plot title/legend/annotated text. As a simple example, let's take a straight line:
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)
在这种情况下,我希望我的文字说渐变为1.0",但是我不确定语法是什么.此外,我将如何在下面添加第二个(和更多个)参数,使其显示为:
In this case, I would like my text to say "The gradient is 1.0", but I'm not sure what the syntax is. Moreover, how would I include the second (and more) parameter(s) below, so that it reads:
渐变为1.0
截距是2.0."
推荐答案
通过 .format()
方法使用字符串格式:
Use string formatting with the .format()
method:
plt.text(0.1, 2.8, "The gradient is {}, the intercept is {}".format(m, c))
其中 m
和 c
是要替换的变量.
Where m
and c
are the variables you want to substitute in.
如果在字符串前加上 f
作为前缀,则可以直接在 Python 3.6 + 中编写这样的变量,
You can directly write the variables like this in Python 3.6+ if you prefix the string with an f
whcih denotes a formatted string literal:
f"the gradient is {m}, the intercept is {c}"
这篇关于添加输入变量以在Python中绘制标题/传奇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!