I am currently facing an issue with matplotlib in combination with PyQt5 which I do not understand at all. Basically, I just want to plot different curves in the same figure, triggered by a QPushButton. I have recreated the problem in the minimal working example below.
Expectation:
Every time I hit the "plot" button, the current figure gets updated with a new line
Outcome:
The first plot works correctly, however after that the figure doesn't get updated with the correct data anymore. If the figure is closed and the button is pressed again, the plot starts to work again. If the code is changed to
fig = plt.figure()
that is, if every time a new figure is created it works as expected. Is this a bug or am I dead-wrong somehow?
The following packages are used for the minimal working example:
matplotlib==3.1.3
PyQt5==5.14.1
pyqt5-tools==5.13.0.1.5
The sample code:
import matplotlib.pyplot as plt
import numpy as np
import sys
from PyQt5 import QtWidgets
class MaterialBrowser(QtWidgets.QMainWindow):
def __init__(self):
super(MaterialBrowser, self).__init__()
self.setEnabled(True)
self.setGeometry(0, 0, 543, 700)
self.setMinimumSize(543, 400)
self.save_button = QtWidgets.QPushButton(self)
self.save_button.setGeometry(100, 100, 110, 32)
self.save_button.setObjectName("plot_button")
self.save_button.setText("Plot")
self.save_button.clicked.connect(self.plot_bhcurve)
self.show()
def plot_bhcurve(self):
t = np.arange(0.0, 2.0, 0.01)
omega = np.random.randint(2, 50)
s = 1 + np.sin(2 * np.pi * omega* t)
fig = plt.figure(num='MYFIGURE')
ax = fig.gca()
ax.plot(t, s, '.-', label=f'mycurve{omega}')
ax.grid(True, which="both")
ax.set_xlabel('Field Strength (A/m)')
ax.set_ylabel('Flux Density (T)')
ax.set_xlim(left=0)
ax.set_ylim(bottom=0)
plt.legend()
plt.show()
app = QtWidgets.QApplication(sys.argv)
materialbrowser = MaterialBrowser()
sys.exit(app.exec_())