MatPlotLib's ion() and draw() not working

python-matplotlib install
matplotlib tutorial
matplotlib plot
matplotlib versions
matplotlib python 3
matplotlib documentation
matplotlib histogram
matplotlib figure

I am trying to plot figures in real time using a for loop. I have the following simple code:

import matplotlib.pyplot as plt

plt.ion()
plt.figure()
for i in range(100):
    plt.plot([i], [i], 'o')
    plt.draw()
    plt.pause(0.0001)

This code does not show the figure until it has finished computing, which I don't want. I want it to draw the figure after every loop. If I replace plt.draw() with plt.show, multiple figures are output in real time, but I want them all to appear in the same figure. Any ideas?

EDIT: I downloaded PyCharm with Anaconda and everything works fine. I guess it's a problem with Spyder since I tried a few different versions of it without success. If anyone has any clue what is causing this problem in Spyder, let me know!

Adapted for your case from : Python realtime plotting

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

fig = plt.figure()
ax = fig.add_subplot(111)

# some X and Y data
x = [0]
y = [0]

li, = ax.plot(x, y,'o')

# draw and show it
fig.canvas.draw()
plt.show(block=False)

# loop to update the data
for i in range(100):
    try:
        x.append(i)
        y.append(i)

        # set the new data
        li.set_xdata(x)
        li.set_ydata(y)

        ax.relim() 
        ax.autoscale_view(True,True,True) 

        fig.canvas.draw()

        time.sleep(0.01)
    except KeyboardInterrupt:
        plt.close('all')
        break

Matplotlib, Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for  Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more information.. Matplotlib produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

This solution example has worked for me on multiple machines. Try adjusting plt.pause(...)

import matplotlib.pyplot as plt
import numpy as np

F = lambda x: np.sin(2*x)

plt.ion()    
x = np.linspace(0, 1, 200)
plt.plot(x, F(x))


for i in range(100):
    if 'ax' in globals(): ax.remove()
    newx = np.random.choice(x, size = 10)
    ax = plt.scatter(newx, F(newx))
    plt.pause(0.05)

plt.ioff()
plt.show()

matplotlib · PyPI, Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more information. Matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is the principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The package is available in binary distribution as well as in the source code form on www.matplotlib.org.

Hey I was having the same problem, I checked other questions and my issue was solved when I plugged a pause into my solution. Here's some example code that worked for me.

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)

The solution was posted here: Matplotlib ion() and subprocesses

Python Plotting With Matplotlib (Guide) – Real Python, Pylab: What Is It, and Should I Use It? The Matplotlib Object Hierarchy; Stateful Versus Stateless Approaches; Understanding plt.subplots() Notation; The “​Figures”  2016-07-28. Copyright © 2015 - 2020 -Pythonspot. | Cookie policy | Terms of use | Privacy policyCookie policy | Terms of use | Privacy policy

The problem - and the solution - is highly dependent on the plot.draw() function within the Python environment and back end, and may even vary in different product releases. It manifests itself in different ways depending on the environment. The problem shows up in many places on stackoverflow with some solutions working for some people and not for others.

The gold standard on my Windows laptop is running the Python from the command line - no IDE, just plain vanilla Python3. draw() as shown in the example always works fine there.

If I try it in Jupyter notebook on the same machine, no amount of draw(), plot.pause(), plot.show(), or any other suggestion works. I tried %matplotlib with notebook, widget and ipympl. Nothing gets drawn until complete end of cell code execution.

Some other sources on stackoverflow suggested using figure.canvas.flush_events(). I had some success with that and investigated further.

The best solution turned out to be to run the draw() at the figure.canvas level instead of the axes or plot level.

You can get the figure by creating your plot with command:

fig, graph, = plt.subplots()

or, if you've already created the plot, as in the code at the top of the ticket, put the following outside the loop:

fig = plt.gcf() #get current figure

Inside the loop, instead of plt.draw(), use

fig.canvas.draw()

It's proven reliable in my Jupyter Notebook environment even when running multiple axes/plots across multiple figures. I can drop in sleep() statements and everything appears when expected.

Your mileage may vary.

matplotlib/matplotlib: matplotlib: plotting with Python, Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more information. Matplotlib is a python library for making publication quality plots using a syntax familiar to MATLAB users. Matplotlib uses numpy for numerics. Output formats include PDF, Postscript, SVG, and PNG, as well as screen display. As of matplotlib version 1.5, we are no longer making file releases available on SourceForge.

Effectively Using Matplotlib, Matplotlib is a valuable but misunderstood foundation of the python data science stack. Matplotlib is home to several different interfaces (ways of constructing a figure) and capable of interacting with a handful of different backends. (Backends deal with the process of how charts are actually rendered, not just structured internally.) While it is comprehensive, some of matplotlib’s own public documentation is seriously out-of

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​  Installing Matplotlib Installing Matplotlib. Before Matplotlib's plotting functions can be used, Matplotlib needs to be installed. Depending on which distribution of Python is installed on your computer, the installation methods are slightly different.

(Tutorial) MATPLOTLIB Tutorial: PYTHON Plotting, This MATPLOTLIB tutorial takes you through the basics of PYTHON data visualization: the anatomy of a PLOT, PYPLOT and PYLAB, and much  If you are interested in contributing to Matplotlib development, running the latest source code, or just like to build everything yourself, it is not difficult to build Matplotlib from source. Grab the latest tar.gz release file from the PyPI files page , or if you want to develop Matplotlib or just need the latest bugfixed version, grab the

Comments
  • try a putting plt.show() after plt.figure().
  • Doing this, I get the output <matplotlib.figure.Figure at 0xa4e77f0>, and the code evaluates as before.
  • How are you executing the script? Calling python stript.py from the bash terminal? Or calling %run from inside an Ipython terminal?
  • I'm using Spyder and am just clicking the run button to run the script.
  • That's not typical behavior. What you have should work. Try running it through Ipython (pythonhosted.org/spyder/ipythonconsole.html). If that doesn't work It might be a problem with the graphics backend (stackoverflow.com/questions/3285193/…).
  • Thanks for the reply. I tried running your code, but I get an error saying show() got an unexpected argument. I read that the block argument was experimental, but I'm not sure why it doesn't work on my Spyder platform.
  • Does it works without the blockkeyword? Apparently it is not working if you already are in an interactive mode.
  • It does work without the block statement, but doing this outputs many different figures. Is there a way to put them all together?
  • This looks like a spyder-specific issue, as it works perfectly fine on my computer. I'm not familiar enough with Spyder to help you