2011-10-29 2 views
23

R에는 절편 (첫 번째 인수) 기울기 (두 번째 인수)의 지정에 따라 플롯에서 선을 그릴 수있는 abline이라는 함수가 있습니다. 예를 들어,matplotlib에서 기울기와 절편을 기준으로 선을 추가 하시겠습니까?

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

여기서 절편이 0이고 기울기가 1 인 줄은 그림의 전체 범위에 걸쳐 있습니다. 이러한 기능이 matplotlib.pyplot에 있습니까?

+2

아니요. 가지고있는 편리한 기능이 될 것입니다. axvspan','axhspan','axhspan','axhspan'과 비슷한 수직적, 수평 적 함수가 있습니다. 그러나 matplotlib의 일반적인 방법은 주어진 슬로프에 선을 그리는 것입니다. 대화식으로 작업하는 경우에는 그 이상으로 확대/축소하십시오.). 프레임 워크 ('matplotlib.transforms')가 있지만 거기에 "올바른"방법 (즉, 어디에서나 줌에 관계없이 항상 축에 걸쳐 있도록)은 실제로 약간 복잡합니다. –

+1

예, 불행합니다 ... Matlab에는이 기능이 없습니다. 반면에 R의 플롯은 고정적입니다 ('abline'이 존재하는'base' 그래픽 시스템). 그래서 걱정할 필요가 없습니다 (그것은 제가 생각하기에 좋고 나쁜 것입니다). – hatmatrix

답변

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() 
+1

글쎄, 어떻게하면 왼쪽 아래 모서리에서 오른쪽 위 모서리로가는 선을 원한다면, 확대/축소 방법에 관계없이'plt.plot ([0,1], [0,1,1] ], transform = plt.gca(). transAxes)'. 이것은 데이터 좌표에서 1 대 1의 기울기를 나타내지는 않을 것이고, 확대 할 때마다 좌측 하단에서 우측 상단으로 항상 갈 것입니다 ... 비록 여러분이 말했듯이, 더 일반적인'abline' 교체는 상호 작용하는 사용을 위해 더 어렵습니다 ... –

+0

아, 이건 transAxes 꽤 흥미 롭습니다. 나는 내가 어떤 점에서 그것을 사용할 것이라고 상상할 수있다. (나는 종종 xlim = ylim이있는 곳이 많다. – hatmatrix

8

나는 콜백에 의지하지 않고 그것을 할 수있는 방법을 알아낼 수 없었다,하지만이 꽤 잘 작동하는 것 같다.

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) 
+0

작은 개선 : 줄 바꾸기 : ax.figure.canvas.draw() 및 self._update_lim (없음) 그래야 플롯이 창을 클릭하지 않고 실제로 업데이트됩니다. – tal

+0

@tal 마침내 matplotlib (1.4.3)'self.axes.draw_artist (self)'를 호출하기 전에 부모 축을 적어도 한 번 렌더해야합니다. 그렇지 않으면'Axert에서 assert self._cachedRenderer is None' 행에'AssertionError'를 얻습니다. draw_artist'. '_update_lim'이 호출 된 후에는 언제든지 추가로 끌기를 삽입 할 수 있습니다. 나는 보통 이것을 직접 인스턴스화하는 것이 아니라 나를 위해 수행하는 편의 함수 내부에서'ABLine'을 초기화합니다. –

26

나는이 질문이 몇 년 전임을 알고 있지만, 받아 들일 수있는 대답이 없으므로, 저에게 도움이되는 것을 추가 할 것입니다.

그래프에 값을 플롯 한 다음 원래 그래프 위에 가장 잘 맞는 선과 플롯의 좌표에 대한 다른 값 집합을 생성 할 수 있습니다. 예를 들어, 다음 코드를 참조하십시오 이러한 솔루션의 많은 데이터를 맞는 플롯에 줄을 추가에 초점을 맞추고있다

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() 
5
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') 
16

. 다음은 기울기와 절편을 기반으로 플롯에 임의의 선을 추가하는 간단한 솔루션입니다.

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, '--') 
관련 문제