Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib animations do not work in PyCharm

I've found various short files that produce animations using matplotlib. In general, they work fine when run from the command line, but in PyCharm I only get a still frame.

I'm asking the same question as Matplotlib does not update plot when used in an IDE (PyCharm). There's an answer posted there, which seems to work for the original asker. When I run that code from the command line, it works fine. From PyCharm, it pauses for a long time (presumably running the animation) and then shows a still frame (that looks like either the beginning or end of the animation).

I'm running Python 3.6.2 (Anaconda) through PyCharm 2017.3.2 (Professional) on a Mac (OS 10.11.6). I created a Python project in PyCharm, pasted that code into a .py file, installed the appropriate libraries (matplotlib 2.0.2, numpy 1.13.1), and ran the program.

The only difference I can see between this and what I did on the command line is that python --version there gives:

Python 3.6.0 :: Anaconda custom (x86_64)

What else could be the problem?

like image 609
Peter Drake Avatar asked Jan 09 '18 21:01

Peter Drake


2 Answers

According to this answer and this ticket, you can disable Show plots in tool window(File->Settings->Tools->Python Scientific) in Pycharm, and I will give an example for this solution.

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

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

image

like image 119
douyu Avatar answered Jan 01 '23 21:01

douyu


The above (or in the link attached) did not work for me, however, i found this works well (running 2.7 with anaconda and ipython console)-

Instead of executing the script normally (using run / Shift+f10), i would first set:

%matplotlib qt5

then execute the script from pycharm console, using

runfile('/path/to/script.py')

resulting in a similar result as if i would do the same from the stand alone ipython console: hover graph

(Note - the figure is animated)

like image 31
Dinari Avatar answered Jan 01 '23 22:01

Dinari