可以通过以下步骤实现:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = 2 * x + 1
plt.scatter(x, y, label='Data Points')
plt.plot(x, y, label='Fit Line')
fit_params = {'slope': 2, 'intercept': 1}
fit_label = 'Fit Line: y = {slope}x + {intercept}'.format(**fit_params)
plt.legend([fit_label])
在这个例子中,我们假设拟合曲线的参数为斜率(slope)为2,截距(intercept)为1。通过将参数值插入到格式化字符串中,我们可以创建一个包含拟合参数的标签。然后,将该标签作为图例的唯一元素传递给plt.legend()
函数。
完整的代码示例如下:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = 2 * x + 1
plt.scatter(x, y, label='Data Points')
plt.plot(x, y, label='Fit Line')
fit_params = {'slope': 2, 'intercept': 1}
fit_label = 'Fit Line: y = {slope}x + {intercept}'.format(**fit_params)
plt.legend([fit_label])
plt.show()
这样,绘图图例中就会显示拟合参数。
领取专属 10元无门槛券
手把手带您无忧上云