views:

72

answers:

3

This is the first time I am using matplotlib and numpy.

Here goes the problem:

If I goto python cli, the intended code works fine. Here is that code

>>> from numpy import *
>>> y = array([1,2])
>>> y = append(y, y[len(y) - 1]+1)
>>> y
array([1, 2, 3])

But if I use it with matplotlib in a script I get this error.

line 26, in onkeypress
y = append(y, y[len(y) - 1]+1)
UnboundLocalError: local variable 'y' referenced before assignment

Here is my script:

from matplotlib.pyplot import figure, show
from numpy import *
figzoom = figure()
axzoom = figzoom.add_subplot(111, xlim=(0,10), ylim=(0, 10),autoscale_on=True)
x = array([1, 2  ])
y = array([1, 10 ])
def onkeypress(event):
    if event.key == "up":
        y = append(y, y[len(y) - 1]+1)
        x = append(x, x[len(x) - 1]  )
        axzoom.plot(x,y)

I tried "append"ing to a different array,say y1, and then y = y1.copy(). But I still get the same error. I must be missing something trivial here???!!!

+2  A: 

It may work if you change the variables to global

def onkeypress(event):
    global y, x
    ...
GWW
+2  A: 

Unless you include global y in your onkeypress() function, the y you're assigning to is scoped locally to the function. You can't use y on the right side of the assignment statement in which you're defining the local variable.

Wooble
+2  A: 

When you assign to a variable inside a function, python creates a new variable that has local scope, and this new variable also hides the global variable.

So, the x and y inside onkeypress are local to the function. Hence, from python's point of view, they are uninitialized, and hence the error.

As GWW points out - declaring x, y as global will solve the problem. Also, if you do not assign x, y any new value, but only use their previously existing value, those values will refer to the global x, y.

Rajan
So, by the same logic "axzoom" too should be global...rite???
future.open
It doesn't have to be declared global. Since the local scope does not have an axzoom variable, the global value is used. Assigning to a variable is different, because it creates a new variable in local scope.
Jouni K. Seppänen
@future.open - the key words in my answer are "When you assign" and "if you do not assign". Since axzoom is not being assigned a value but its value is being used, it still refers to the global variable.
Rajan
got it...its clear now
future.open