如何在 Python 的 plt.title 中添加一个变量?
要在 Python 的 plt.title() 中添加一个变量,可以按照以下步骤进行操作 −
- 使用 numpy 和 num (一个变量)计算 y,并将这个变量设置在标题中,创建 x 和 y 的数据点。
-
使用红色的 plot() 方法绘制 x 和 y 数据点。
-
将曲线的标题设置为变量 num。
-
使用 show() 方法来显示图像。
例子
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 10)
num = 2
y = num ** x
plt.plot(x, y, c='red')
plt.title(f"y=%d^x" % num)
plt.show()