在R中,有一個稱爲abline
的函數,其中可以根據截距(第一個參數)斜率(第二個參數)的指定在曲線上繪製直線。例如,在matplotlib中添加基於斜率和截距的線?
plot(1:10,1:10)
abline(0,1)
其中截距爲0且斜率爲1的線橫跨繪圖的整個範圍。 matplotlib.pyplot
有這樣的功能嗎?
在R中,有一個稱爲abline
的函數,其中可以根據截距(第一個參數)斜率(第二個參數)的指定在曲線上繪製直線。例如,在matplotlib中添加基於斜率和截距的線?
plot(1:10,1:10)
abline(0,1)
其中截距爲0且斜率爲1的線橫跨繪圖的整個範圍。 matplotlib.pyplot
有這樣的功能嗎?
對於(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()
好吧,如果你只是想要一條從左下角到右上角的線,不管你如何縮放,那麼你可以做'plt.plot([0,1],[0,1 ],transform = plt.gca()。transAxes)'。但這不會代表數據座標中的1到1斜率,並且它將從左下角到右上角,無論您放大到哪裏......就像您所說的那樣,儘管如此,更通用的「abline」替換更難交互使用... –
啊,這是transAxes相當有趣。我可以想象,我會在某個時候使用它...(我經常有很多地方xlim = ylim,或者應該是)。 – hatmatrix
我想不通的方式來做到這一點,但訴諸回調,但這似乎工作得很好。
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)
小改進:換行: ax.figure.canvas.draw()和 self._update_lim(無) 所以劇情實際更新無需點擊窗口 – tal
@tal最後在我的版本的matplotlib( 1.4.3)在調用'self.axes.draw_artist(self)'之前,至少需要渲染父軸,否則我會在'Axes中斷言'assert self._cachedRenderer不是None'這行'AssertionError'。 draw_artist'。在調用_update_lim之後,您總是可以插入額外的繪圖。我通常從一個方便的函數裏面初始化'ABLine',這個方法對我來說很有用,而不是直接實例化它。 –
我知道這個問題已經有幾年了,但由於沒有被接受的答案,所以我會加入對我有用的東西。
您可以將圖中的值繪製出來,然後爲最佳擬合線的座標生成另一組值,並將其繪製在原始圖上。例如,請看下面的代碼:
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()
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')
很多解決方案都是着眼於增加一個行適合該數據的陰謀。這裏有一個簡單的解決方案,用於根據斜率和截距將任意線添加到繪圖。
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, '--')
不,沒有。這將是一個方便的功能。這裏有'axvline','axvspan','axhline'和'axhspan',它們具有類似的垂直和水平功能,但matplotlib中的常用方法是在給定斜率處繪製一條線(這意味着您最終會如果您正在交互式工作,請將它縮小超過它。)。儘管框架('matplotlib.transforms')在那裏,那麼這樣做的「正確」方式(也就是說,無論放大哪裏都始終跨越軸)實際上有點複雜。 –
是的,這是不幸的... Matlab也沒有這個功能。另一方面,R的圖是靜態的('基線'圖形系統存在'abline'),所以不用擔心那裏(我猜想這是一件好事和壞事)。 – hatmatrix