pyplot plot freezes (not responding)

Question:

I am struggling with pyplot from the matlpotlib library. The figure freezes already when I try to create the plot:

plt.figure()
plt.ion()
ax1 = plt.subplot(211) #Here it freezes
plt.title('test', fontsize=8)
plt.xlim(-1700, 1700)
plt.ylabel('x-axis')
plt.xlabel('y-axis')
plt.grid()
plt.show()
...do something else

I have only worked with Pyqt plots, but this time I would like to solve my Problem without multithreading since I do not care if the plot stops my code for a short moment. The problem is, the script does not stop but continues to run and does not wait until the figure is completely created. (time.sleep() does not help). Is there a solution without threads?

Cheers,
James

Ps.: If I add a breakpoint after the code and run in debug mode, there is no Problem (obviously).

Asked By: Camill Trüeb

||

Answers:

Is this one working as you want it?

import matplotlib.pyplot as plt

plt.figure()
plt.ion()
ax1 = plt.subplot(211) #Here it freezes
plt.title('test', fontsize=8)
plt.xlim(-1700, 1700)
plt.ylabel('x-axis')
plt.xlabel('y-axis')
plt.grid()
plt.draw() # draw the plot
plt.pause(5) # show it for 5 seconds
print("Hallo") # continue doing other stuff

Using plt.clf is a simple addon to close figure after the plot is completed.

import matplotlib.pyplot as plt

plt.figure()
plt.ion()
ax1 = plt.subplot(211) 
plt.title('test', fontsize=8)
plt.xlim(-1700, 1700)
plt.ylabel('x-axis')
plt.xlabel('y-axis')
plt.grid()
plt.show()
plt.clf() # Here is another path
Answered By: Drew Bennett

For me, it worked using:

import matplotlib
matplotlib.use('TkAgg')
Answered By: Sandro Gouveia

fig = plt.figure() will cause the freeze for my PyQt5 as well.

I don’t the exactly reasons but find nice workaround and works for me.

Workaround:

from matplotlib.Figure import Figure
fig1 = Figure()
ax1 = fig1.add_subplot()

You can find more examples from
https://pythonspot.com/pyqt5-matplotlib/

Answered By: user15071174
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.