在此post中,我询问了如何在pyqt5 gui中嵌入一个matplotlib图,该图现在可以正常工作。现在,我还有一个直到现在还无法解决的问题:如何更新图形?
我试图通过调用来更新画布
self.plotWidget = FigureCanvas(fig)
每次都带有新的“ fig”对象,但是什么也没有发生。所以我试图将其添加到布局中
self.lay.addWidget(self.plotWidget)
,但这会向窗口小部件添加另一个子图。我猜想我必须在更新之前清除以前的图,但是我不知道该怎么做。
使用更新方法重新绘制的正确策略是什么?
谢谢!
# -*- coding: utf-8 -*-
import sys
import numpy as np
from PyQt5 import QtCore, QtWidgets, uic
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pylab as plt
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
uic.loadUi('test.ui', self)
# test data
data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])
fig, ax1 = plt.subplots()
bins = np.arange(0.6, 1.62, 0.02)
n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)
# plot
self.plotWidget = FigureCanvas(fig)
self.lay = QtWidgets.QVBoxLayout(self.content_plot)
self.lay.setContentsMargins(0, 0, 0, 0)
self.lay.addWidget(self.plotWidget)
# add toolbar
self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))
# button event
self.pushButton.clicked.connect(self.update)
# show window
self.show()
#########################################
def update(self):
data = np.array([0.1,0.1,0.1,0.1,0.3,0.3,1.7,1.7,1.7,1.7])
fig, ax1 = plt.subplots()
bins = np.arange(0.6, 1.62, 0.02)
n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)
# show plot in canvas
self.plotWidget = FigureCanvas(fig)
self.toolbarWidget = NavigationToolbar(self.plotWidget, self)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
答案 0 :(得分:1)
您不应创建新图形,而应重新使用已有的轴。这意味着您必须先保留对该对象的引用。
我现在无法测试代码,但是您应该做类似的事情
def __init__(self):
(...)
self.fig, self.ax = plt.subplots()
(...)
def update(self):
data = (...)
self.ax.cla() # clear the axes content
self.ax.hist(...)
self.fig.canvas.draw_idle() # actually draw the new content