Search code examples
pythonaxispython-interactive

Axis edits in interactive mode ion() in matplotlib are ignored - scope problem?


I would like to make a plot from a data array that grows in time. I found ion() to redraw my plot, adding new points. Now, adding a new point should erase an old one and to achieve that I had to add clf(). This again means I have to reset my axis edits every time I plot, but it ignores every modification that depends on the axis handle. I was wondering if this is a scope problem because of the function I call? I am new to python and would also appreciate feedback in case there is a more straightforward approach than the one chosen.

I tried to pass the axis handle through the different functions in hope this would change things, but without success.

import matplotlib.pyplot as plt
import matplotlib.ticker as tck
from time import time

x, y = [], []
counter = 0
plt.ion()
fig, ax1 = plt.subplots()      # ax1 is not used

def axis(ax):
    ax.set_label("Time [s]")
    ax.yaxis.set_major_locator(tck.MultipleLocator(base=0.5))

def plot():
    plt.clf()
    ax = plt.gca()
    axis(ax)
    if len(y) < 3:
        plt.plot(x, y, c='r')
    else:
        plt.plot(x[-3:], y[-3:], c='r')
    plt.draw()
    return ax


for i in range(0,10):
    x.append(time())
    y.append(counter)
    print(i, '\n')
    ax = plot()
    counter +=1
    plt.pause(1)

Solution

  • Passing of ax not needed. Substituting plt.clf() with ax1.clear() solved the issue.