您好我试图将自定义图形添加到我的pyqt界面。它没有显示任何数据,但显示占位符matplotlib图。有什么帮助?!此外,如果我只绘制图形数据而不将其放入PYQT,它会显示出来。谢谢!
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
#self.axes = fig.add_subplot(111)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.compute_initial_figure()
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self):
pass
class MyStaticMplCanvas(MyMplCanvas):
def mystatic(self, parent=None):
super(MyStaticMplCanvas, self).__init__(parent)
rate,data = read('test.wav') # reading
subplot(411)
self.plot(range(len(data)),data)
subplot(412)
self.specgram(data, NFFT=128, noverlap=0) # small window
subplot(413)
self.specgram(data, NFFT=512, noverlap=0)
subplot(414)
self.specgram(data, NFFT=1024, noverlap=0) # big window
self.show()
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
l = QtGui.QVBoxLayout(self.main_widget)
sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
l.addWidget(sc)
答案 0 :(得分:2)
在您提供的代码示例中,没有调用用于绘制数据的 mystatic 方法。因此,您的身材上没有任何内容。
此外,您似乎正在使用 pyplot 界面直接调用subplot
和plot
来绘制数据,例如在 mystatic 中。在应用程序中嵌入mpl数字时,建议mpl documentation坚持使用面向对象的API。
我已根据您提供的代码生成了一个最小的工作示例,该代码遵循上述文档中提供的准则。希望它有所帮助。
from PyQt4 import QtGui
import sys
import numpy as np
import matplotlib as mpl
mpl.use('Qt4Agg')
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = mpl.figure.Figure(figsize=(width, height), dpi=dpi)
fig.set_tight_layout('tight')
super(MyMplCanvas, self).__init__(fig)
class MyStaticMplCanvas(MyMplCanvas):
def mystatic(self, parent=None):
x, y = np.random.rand(50), np.random.rand(50)
ax1 = self.figure.add_subplot(411)
ax1.plot(x,y, '.')
ax2 = self.figure.add_subplot(412)
ax2.plot(x,y, '.')
ax3 = self.figure.add_subplot(413)
ax3.plot(x,y, '.')
ax4 = self.figure.add_subplot(414)
ax4.plot(x,y, '.')
if __name__ == '__main__' :
app = QtGui.QApplication(sys.argv)
w = MyStaticMplCanvas(width=5, height=6, dpi=100)
w.mystatic()
w.show()
sys.exit(app.exec_())
导致: