gpt4 book ai didi

python - PYQT 和嵌入 matplotlib : Graph not showing

转载 作者:行者123 更新时间:2023-12-01 04:29:09 24 4
gpt4 key购买 nike

您好,我正在尝试将自定义图形添加到我拥有的 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)

最佳答案

在您提供的代码示例中,没有调用用于绘制数据的 mystatic 方法。因此,您的图形上没有绘制任何内容。

此外,您似乎正在使用pyplot接口(interface)通过直接调用subplotplot来绘制数据,例如神秘的。在应用程序中嵌入 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_())

结果是:

enter image description here

关于python - PYQT 和嵌入 matplotlib : Graph not showing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com