Matplotlib interactive mode won't work, no matter what I do

3.3k Views Asked by At

I'm using python 3.7.7 and matplotlib 3.3.1 on Pycharm community 2020.1

I want to draw a figure and let the user decide if he likes that figure, by giving some console input. That means I need matplotlib to work in the interactive mode. I tried the following many approaches, that I've found online:

plt.ion() alone

import matplotlib.pyplot as plt
plt.ion()
plt.plot([1,2,3])
plt.show()


print('is this fig good? (y/n)')
x = input()
if x=="y":
    plt.savefig(r'C:\figures\papj.png')
else:
    print("big sad")

this results only in blank figure window. If you click that window too much, it will "stop responding".

plt.show(block=False)

import matplotlib.pyplot as plt    
plt.plot([1,2,3])
plt.show(block=False) 

print('is this fig good? (y/n)')
x = input()
if x=="y":
    plt.savefig(r'C:\figures\papj.png')
else:
    print("big sad")

Same result as previously.

plt.draw()

import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.draw()


print('is this fig good? (y/n)')
x = input()
if x=="y":
    plt.savefig(r'C:\figures\papj.png')
else:
    print("big sad")

This does nothing, just displays the question in the console.

plt.ion() and plt.draw()

import matplotlib.pyplot as plt
plt.ion()
plt.plot([1,2,3])
plt.draw()


print('is this fig good? (y/n)')
x = input()
if x=="y":
    plt.savefig(r'C:\figures\papj.png')
else:
    print("big sad")

Again, blank figure window, that crashes after clicking on it.

ion() and block=False

import matplotlib.pyplot as plt
plt.ion()
plt.plot([1,2,3])
plt.show(block=False)


print('is this fig good? (y/n)')
x = input()
if x=="y":
    plt.savefig(r'C:\figures\papj.png')
else:
    print("big sad")

Again, blank figure window, that crashes after clicking on it.

What can I do to make it work correctly?

1

There are 1 best solutions below

3
On BEST ANSWER

You need to add a pause to avoid the figure being "locked" and to get to the user input while the Figure is still being displayed.

import matplotlib.pyplot as plt
plt.ion()
plt.plot([1,2,3])
plt.pause(0.01) # <---- add pause
plt.show()

print('is this fig good? (y/n)')
x = input()
if x=="y":
    plt.savefig(r'C:\figures\papj.png')
else:
    print("big sad")

If you want something more complicated than this, you would have a loop where you redraw the figure in each iteration (e.g. if you want to show a different figure) and pause right at the end of each iteration.