0

I have the following code that generates an animated plot:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

x = []
y = []
t = 0

fig, ax = plt.subplots()
line, = ax.plot([0,0])

ax.set_ylim((-2,2))
ax.set_xlim((0,10))

def animate(i):
    global x,y,t
    line.set_ydata(y)
    line.set_xdata(x)
    x.append(t)
    y.append(np.sin(t))
    t += 0.05
    return line,


def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init, interval=25, blit=True)
plt.show()

How can I make it so that the plot is scaled to fit the data? I would like the axes and scale to automatically adjust.

888
  • 291
  • 3
  • 11
  • I have figured out how to scale the data with `ax.relim()` and `ax.autoscale_view()`, but the ticks do not change. – 888 Sep 05 '18 at 22:04
  • 1
    If you want to change the plot limits (e.g. via `ax.relim()` and `ax.autoscale_view()`) you need to redraw the axes. This is prevented by `blit=True`. Blitting only makes sense if you want to redraw a limited portion of your figure. Set `blit=False` to update the complete canvas and with it the axes scales. – ImportanceOfBeingErnest Sep 05 '18 at 22:07
  • @ImportanceOfBeingErnest Thanks, but turning off blitting hurts performance so much my fan kicks on. Is there a way to update the ticks without causing such a large drop in performance? – 888 Sep 05 '18 at 22:18
  • Do you not observe an equally large drop in performance already when using `ax.relim() and ax.autoscale_view()`? I guess you can write a custom function to blit the axes as well, but of course the larger the area to blit the closer it gets to redrawing everything. – ImportanceOfBeingErnest Sep 05 '18 at 22:23
  • My CPU usage stays at around 15% when using blitting, and jumps up to around 40% with blitting turned off. Where can I figure out how to scale the axes while keeping my laptop cool? – 888 Sep 05 '18 at 22:25
  • Let me put it like this: Matplotlib does not provide any means to blit the axes. But you may write a custom function that does. You would start by understanding the blitting mechanism and looking around for examples that use manual blitting (e.g. [this one](https://stackoverflow.com/questions/40126176/fast-live-plotting-in-matplotlib-pyplot)). You may then extend this to use a larger bounding box. However I still have the feeling that once you blit the axes performance would equally drop. One would need to do it in order to find out. – ImportanceOfBeingErnest Sep 05 '18 at 22:39
  • Okay, thank you for the help! I don't think I'm skilled enough to do that, so I'll look for a different library for liveplotting. – 888 Sep 05 '18 at 22:49

0 Answers0