1

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???!!!

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
2

It may work if you change the variables to global

def onkeypress(event):
    global y, x
    ...

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.