abline plot?

Hi,

I wrote an abline_plot function, and I’m curious if what I’m doing is the best way to go about this. I tried unsuccessfully to get the transforms to do what I want, but I’m not sure if it’s possible. What I came up with is to use callbacks to draw an “infinite” line. It works, but it seems a bit sluggish. Does anyone have any thoughts on improvements, anything I’m missing, or an alternative implementation? The only problem I see right now is that it assumes ax only has one ABLine2D child.

Thanks,

Skipper

import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt

Generate some data

intercept = 1.3
slope = .5
x = np.random.random(25)

y_noise = intercept + slope * x + np.random.randn(25)

Set up the plot

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y_noise)

class ABLine2D(Line2D):

def update_datalim(self, ax):

    ax.set_autoscale_on(False)

    children = ax.get_children()
    abline = [children[i] for i in range(len(children))
               if isinstance(children[i], ABLine2D)][0]
    x = ax.get_xlim()

    y = [x[0]*slope+intercept, x[1]*slope+intercept]
    abline.set_data(x,y)
    ax.figure.canvas.draw()

line = ABLine2D(x, y)
ax.add_line(line)
ax.callbacks.connect(‘xlim_changed’, line.update_datalim)

ax.callbacks.connect(‘ylim_changed’, line.update_datalim)

plt.show()

Hi,

I wrote an abline_plot function, and I’m curious if what I’m doing is the best way to go about this. I tried unsuccessfully to get the transforms to do what I want, but I’m not sure if it’s possible. What I came up with is to use callbacks to draw an “infinite” line. It works, but it seems a bit sluggish. Does anyone have any thoughts on improvements, anything I’m missing, or an alternative implementation? The only problem I see right now is that it assumes ax only has one ABLine2D child.

Hmm, it actually seems to handle multiple ablines ok, though I don’t know if it’s robust. Should ABLine2D take a slope and intercept in its instantiation?

···

On Sun, Apr 1, 2012 at 4:23 PM, Skipper Seabold <jsseabold@…2015…87…> wrote:

Thanks,

Skipper

import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt

Generate some data

intercept = 1.3
slope = .5
x = np.random.random(25)

y_noise = intercept + slope * x + np.random.randn(25)

Set up the plot

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y_noise)

class ABLine2D(Line2D):

def update_datalim(self, ax):



    ax.set_autoscale_on(False)

    children = ax.get_children()
    abline = [children[i] for i in range(len(children))
               if isinstance(children[i], ABLine2D)][0]
    x = ax.get_xlim()



    y = [x[0]*slope+intercept, x[1]*slope+intercept]
    abline.set_data(x,y)
    ax.figure.canvas.draw()

line = ABLine2D(x, y)
ax.add_line(line)
ax.callbacks.connect(‘xlim_changed’, line.update_datalim)

ax.callbacks.connect(‘ylim_changed’, line.update_datalim)

plt.show()