Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib ion() function fails to be interactive

Tags:

matplotlib

I have problem with interactive feature of Matplotlib. I ran the following program and received a freezing empty graph window.

import matplotlib.pyplot as plt import numpy as np  plt.ion() x = np.arange(0, 4*np.pi, 0.1) y = [np.sin(i) for i in x] plt.plot(x, y, 'g-', linewidth=1.5, markersize=4) plt.show() 

If I removed 'plt.ion()' statement, then it worked just fine. I use IDLE and the Matplotlib version 1.2.x package is installed in Python 3.2.2.

I expect it to be interactive, but instead I got an unfriendly non-interactive window. Can someone shed some light of what I am missing? Thank you in advance.

like image 228
kaosad Avatar asked Oct 01 '12 08:10

kaosad


People also ask

What does PLT ion () do?

ion() in Python. Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.

Are matplotlib graphs interactive?

The interactivity is not only limited to 2D plots but can also be observed in 3D plots. The code has been taken from matplotlib's official documentation.

What is interactive mode in matplotlib?

Matplotlib can be used in an interactive or non-interactive modes. In the interactive mode, the graph display gets updated after each statement. In the non-interactive mode, the graph does not get displayed until explicitly asked to do so.


2 Answers

I bumped into this link found here, which answers my problem.

It seems that after turning on interactive mode through plt.ion(), pyplot needs to be paused temporarily for it to update/redraw itself through plt.pause(0.0001). Here is what I did and it works!

>>> import matplotlib.pyplot as plt >>> import numpy as np >>> plt.ion() >>> x = np.arange(0, 4*np.pi, 0.1) >>> y = [np.sin(i) for i in x] >>> plt.plot(x, y, 'g-', linewidth=1.5, markersize=4) >>> plt.pause(0.0001)          >>> plt.plot(x, [i**2 for i in y], 'g-', linewidth=1.5, markersize=4) >>> plt.pause(0.0001) >>> plt.plot(x, [i**2*i+0.25 for i in y], 'r-', linewidth=1.5, markersize=4)  >>> plt.pause(0.0001) 

If you tried that in your IDLE console, notice that up to this point everything got displayed except that the graph window freezes and cannot exit. To unfreeze it type the following last statement

>>> plt.show(block=True) 

Now the window can be closed.

like image 192
kaosad Avatar answered Sep 24 '22 03:09

kaosad


I am having the exact same problem. In ipython there is the magic %matplotlib, which solved the problem for me. At least now I can type plt.figure() (assuming that import matplotlib.pyplot as plt has been called) and get a fully interactive responsive figure.

However, I would still be interested to know what this magic imports exactly to be able to understand the problem.

like image 30
Chris Avatar answered Sep 23 '22 03:09

Chris