如何在 Matplotlib 中根据斜率和截距添加线? [英] How to add line based on slope and intercept in Matplotlib?
本文介绍了如何在 Matplotlib 中根据斜率和截距添加线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在R中,有一个名为 abline
的函数,其中可以根据截距(第一个参数)和斜率(第二个参数)的指定在绘图上绘制一条线.例如,
In R, there is a function called abline
in which a line can be drawn on a plot based on the specification of the intercept (first argument) and the slope (second argument). For instance,
plot(1:10, 1:10)
abline(0, 1)
其中截距为0且斜率为1的线跨越了图的整个范围.Matplotlib中有这样的功能吗?
where the line with an intercept of 0 and the slope of 1 spans the entire range of the plot. Is there such a function in Matplotlib?
推荐答案
很多这些解决方案都专注于在绘图中添加一条适合数据的线.这是根据斜率和截距向图中添加任意线的简单解决方案.
A lot of these solutions are focusing on adding a line to the plot that fits the data. Here's a simple solution for adding an arbitrary line to the plot based on a slope and intercept.
import matplotlib.pyplot as plt
import numpy as np
def abline(slope, intercept):
"""Plot a line from slope and intercept"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = intercept + slope * x_vals
plt.plot(x_vals, y_vals, '--')
这篇关于如何在 Matplotlib 中根据斜率和截距添加线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文