如何在Matplotlib中基于斜率和截距添加线?

时间:2011-10-29 19:39:13

标签: python matplotlib

在R中,有一个名为abline的函数,其中可以根据截距(第一个参数)和斜率(第二个参数)的规范在图上绘制一条线。例如,

plot(1:10, 1:10)
abline(0, 1)

其中截距为0且斜率为1的直线跨越整个绘图范围。 Matplotlib中有这样的功能吗?

11 个答案:

答案 0 :(得分:46)

很多这些解决方案都专注于在符合数据的情节中添加一条线。这是一个简单的解决方案,可以根据斜率和截距在绘图中添加任意一条线。

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, '--')

答案 1 :(得分:30)

我知道这个问题已有几年了,但由于没有接受的答案,我会添加对我有用的问题。

您可以在图表中绘制值,然后为最佳拟合线的坐标生成另一组值,并在原始图形上绘制。例如,请参阅以下代码:

import matplotlib.pyplot as plt
import numpy as np

# Some dummy data
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 3, 2, 5, 7, 9]

# Find the slope and intercept of the best fit line
slope, intercept = np.polyfit(x, y, 1)

# Create a list of values in the best fit line
abline_values = [slope * i + intercept for i in x]

# Plot the best fit line over the actual values
plt.plot(x, y, '--')
plt.plot(x, abline_values, 'b')
plt.title(slope)
plt.show()

答案 2 :(得分:9)

如果不诉诸回调,我无法想办法,但这似乎运作得相当好。

import numpy as np
from matplotlib import pyplot as plt


class ABLine2D(plt.Line2D):

    """
    Draw a line based on its slope and y-intercept. Additional arguments are
    passed to the <matplotlib.lines.Line2D> constructor.
    """

    def __init__(self, slope, intercept, *args, **kwargs):

        # get current axes if user has not specified them
        if not 'axes' in kwargs:
            kwargs.update({'axes':plt.gca()})
        ax = kwargs['axes']

        # if unspecified, get the current line color from the axes
        if not ('color' in kwargs or 'c' in kwargs):
            kwargs.update({'color':ax._get_lines.color_cycle.next()})

        # init the line, add it to the axes
        super(ABLine2D, self).__init__([], [], *args, **kwargs)
        self._slope = slope
        self._intercept = intercept
        ax.add_line(self)

        # cache the renderer, draw the line for the first time
        ax.figure.canvas.draw()
        self._update_lim(None)

        # connect to axis callbacks
        self.axes.callbacks.connect('xlim_changed', self._update_lim)
        self.axes.callbacks.connect('ylim_changed', self._update_lim)

    def _update_lim(self, event):
        """ called whenever axis x/y limits change """
        x = np.array(self.axes.get_xbound())
        y = (self._slope * x) + self._intercept
        self.set_data(x, y)
        self.axes.draw_artist(self)

答案 3 :(得分:7)

X = np.array([1, 2, 3, 4, 5, 6, 7])
Y = np.array([1.1,1.9,3.0,4.1,5.2,5.8,7])

scatter (X,Y)
slope, intercept = np.polyfit(X, Y, 1)
plot(X, X*slope + intercept, 'r')

答案 4 :(得分:4)

我认为对于(intercept, slope) (0, 1)的情况,可以使用并扩展以下函数以适应其他斜率和截距,但是如果更改轴限制或返回自动缩放,则不会重新调整上。

def abline():
    gca = plt.gca()
    gca.set_autoscale_on(False)
    gca.plot(gca.get_xlim(),gca.get_ylim())

import matplotlib.pyplot as plt
plt.scatter(range(10),range(10))
abline()
plt.draw()

答案 5 :(得分:4)

此功能似乎将成为版本3.3.0的一部分:

matplotlib.axes.Axes.axline

例如,您将能够使用

在点(0, 0)(1, 1)上画一条红线
axline((0, 0), (1, 1), linewidth=4, color='r')

答案 6 :(得分:2)

截至 2021 年,在 matplotlib 3.3.4 中,它支持绘制带有斜率值和一个点的线。

fig, ax = plt.subplots()

ax.axline((0, 4), slope=3., color='C0', label='by slope')
ax.set_xlim(0, 1)
ax.set_ylim(3, 5) 
ax.legend()

enter image description here

答案 7 :(得分:1)

kite.com启发的简短答案:

plt.plot(x, s*x + i) 

可复制的代码:

import numpy as np
import matplotlib.pyplot as plt
i=3        # intercept
s=2        # slope
x=np.linspace(1,10,50)      # from 1 to 10, by 50
plt.plot(x, s*x + i)        # abline
plt.show()

2x+3

答案 8 :(得分:1)

我想扩展David Marx的答案,我们要确保倾斜线不会在原始绘图区域上扩展。 由于x轴限制用于计算斜线的y数据,因此我们需要确保计算出的y数据不会扩展给定的ymin-ymax范围。如果确实裁剪了显示的数据。

def abline(slope, intercept,**styles):
"""Plot a line from slope and intercept"""

axes = plt.gca()
xmin,xmax = np.array(axes.get_xlim())
ymin,ymax = np.array(axes.get_ylim()) # get also y limits
x_vals = np.linspace(xmin,xmax,num=1000) #increased sampling (only actually needed for large slopes)
y_vals = intercept + slope * x_vals
locpos = np.where(y_vals<ymax)[0] # if data extends above ymax
locneg = np.where(y_vals>ymin)[0] # if data extends below ymin
# select most restricitive condition 
if len(locpos) >= len(locneg):
    loc = locneg
else: 
    loc = locpos
plt.plot(x_vals[loc], y_vals[loc], '--',**styles)
return y_vals

答案 9 :(得分:0)

这是我想出的一种可能的解决方法:假设我将截距坐标存储为x_intercepty_intercept,以及斜率( m )另存为my_slope,这可以通过著名的等式 m =(y2-y1)/(x2-x1) 找到,或以任何方式进行管理找到它。

使用另一条著名的通用方程式 y = mx + q ,我定义了函数find_second_point,该函数首先计算 q (因为已知 m x y ),然后计算出另一个属于那条线。

一旦有了两个点(最初的x_intercepty_intercept和新发现的new_xnew_y),我就简单地绘制了通过这两个点的线段。这是代码:

import numpy as np
import matplotlib.pyplot as plt

x_intercept = 3  # invented x coordinate
y_intercept = 2  # invented y coordinate
my_slope = 1  # invented slope value

def find_second_point(slope,x0,y0):
    # this function returns a point which belongs to the line that has the slope 
    # inserted by the user and that intercepts the point (x0,y0) inserted by the user
    q = y0 - (slope*x0)  # calculate q
    new_x = x0 + 10  # generate random x adding 10 to the intersect x coordinate
    new_y = (slope*new_x) + q  # calculate new y corresponding to random new_x created

    return new_x, new_y  # return x and y of new point that belongs to the line

# invoke function to calculate the new point
new_x, new_y = find_second_point(my_slope , x_intercept, y_intercept )

plt.figure(1)  # create new figure
plt.plot((x_intercept, new_x),(y_intercept, new_y), c='r', label='Segment')
plt.scatter(x_intercept, y_intercept, c='b', linewidths=3, label='Intercept')
plt.scatter(new_x, new_y, c='g', linewidths=3, label='New Point')
plt.legend()  # add legend to image

plt.show()

这是代码生成的图像:

result image

答案 10 :(得分:0)

可以简单地创建一个列表,其中包含从特定截距和斜率获得的直线方程。将这些值放在一个列表中,并根据您想要的任何一组数字绘制它。例如-(Lr 是线性回归模型)

te= []
for i in range(11):
    te.append(Lr.intercept_ + Lr.coef_*i)
plt.plot(te, '--')

完成工作。