I am building an application that embeds a matplotlib figure into the GUI. The problem is that my app is crashing as soon as I add anything from matplotlib into my code (ex
I am still getting crashes with this:
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
f = plt.figure()
plt.plot(x, y)
f.show()
plt.pause(0.0001)
The window with a sinappears and then the kernel freezes. Windows 10 with Anaconda3
You need to set the TkAgg backend explicitly. I could reproduce your bug. With the following code, the problem is resolved.
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
Note that setting the TkAgg backend after importing pyplot does not work either; it crashes too. You need to set it before importing pyplot. (Tested with MPL 1.4.3, tkinter.TkVersion 8.6)
Once i updated to the latest Python environment (3.8.2) this error went away without the need to use matplotlib.use("TkAgg").
If you don't want to edit the code, you can use set the following environment variable that matplotlib
is reading:
MPLBACKEND=TkAgg
This way, no matter when you import pyplot
, it'll work
@DonCristobal's answer helped me and therefore I tried to upvote or add a comment to it but stackoverflow prevents me from doing any of that citing certain points I must reach before I can comment or upvote. The solution suggested by @DonCristobal worked for my configuration given below:
Mac catalina, python 3.6 & matplotlib 3.0.3
Here is what i did -
Modified
import matplotlib.pyplot as plt
to
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt