Matplotlib animation either freezes after a few frames or just doesn't work

前端 未结 8 1324
悲哀的现实
悲哀的现实 2020-12-18 06:04

I\'ve been trying for hours to get this simple script working, but nothing I do seems to help. It\'s a slight modification of the most basic animated plot sample code from t

相关标签:
8条回答
  • 2020-12-18 07:05

    Typically, GUI frameworks need to 'own' the main loop of the program. Sitting in a tight loop with sleeps to delay iterations will usually 'break' GUI applications (your problem description is consistent with typical breakage along these lines). It's possible that the matplotlib devs have implemented some behind the scenes logic to pevent these lockups from happening for certain toolkits but restructuring your program slightly should eliminate any chance of mainloop ownership being the problem (which is very likely I think). The matplotlib animation wiki also suggests using native event loops for anything nontrivial (probably for this reason)

    Rather than sitting in a loop with sleeps, I suggest that, instead, you use the GUI toolkit to schedule a function call after a certain delay.

    def update_function():
        # do frame calculation here
    
    refresh_timer = QtCore.QTimer()
    QtCore.QObject.connect( refresh_timer, QtCore.SIGNAL('timeout()'), update_function )
    refresh_timer.start( 1.0 / 30 ) # have update_function called at 30Hz
    

    Looking at the matplotlib documentation suggests that it may be possible to use their API natively but I couldn't find any good examples using just a quick search.

    0 讨论(0)
  • 2020-12-18 07:07

    After many hours fighting with this same issue I think I've found the answer: To do these simple animations with matplotlib you can only use the GTKAgg backend. This is stated as a passing remark in the scipy cookbook, but I think it should be stressed more clearly. When I use it, I can run your animations until the end without freezes or any other problem.

    Beware that to use this backend you need to install PyGTK. I don't know what else you need on Windows (because I'm on Linux) but that seems the minimum. Besides, if you want to use it by default you have to add this line to your matplotlibrc (on Linux placed on ~/.matplotlib/matplotlibrc):

    backend      : GTKAgg
    

    To use the other backends you need to follow the official matplotlib examples, but that means you have to build a mini-gui application just to run a simple animation, and I find that quite awful!

    0 讨论(0)
提交回复
热议问题