[英]How to show matplotlib.pyplot in qt widget?
I want to show the pyplot image in widget (QWidget) that I put in a gui designed in QtDesigner: 我想显示我在QtDesigner中设计的gui中放置的小部件(QWidget)中的pyplot图像:
When I push the Çiz
button I want to show the image that I can create in python with that code: 当我按下
Çiz
按钮时,我想显示可以使用该代码在python中创建的图像:
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)
x_fit = np.linspace(min(x), max(x), 10000)
y_fit = [f(_x) for _x in x_fit]
plt.plot(x, y)
plt.plot(x_fit, y_fit)
plt.show()
EDIT 编辑
I made some changes according to the answer but I have new problems. 我根据答案进行了一些更改,但遇到了新问题。
After I promote it: 推广后:
I rearrange my code below: 我在下面重新排列我的代码:
# calculate polynomial and r
self.x_fit = np.linspace(min(self.itemX), max(self.itemY), 10000)
self.y_fit = [f(_x) for _x in self.x_fit]
self._dlg.plotwidget.plot(self.itemX, self.itemY)
self._dlg.plotwidget.plot(self.x_fit, self.y_fit)
self.itemX
is x values in a list. self.itemX
是列表中的x个值。
self.itemY
is y values in a list. self.itemY
是列表中的y值。
self._dlg
is the MainWindow that you see. self._dlg
是您看到的MainWindow。
When I try to open that window I get this error message: 当我尝试打开该窗口时,出现以下错误消息:
Sorry I don't exactly answer the question but I don't use matplotlib.pyplot
with pyqt. 抱歉,我没有完全回答问题,但是我没有将pyqt与
matplotlib.pyplot
一起使用。 I recommend using pyqtgraph ( http://pyqtgraph.org ), which is quite convenient and powerful. 我建议使用pyqtgraph( http://pyqtgraph.org ),它非常方便且功能强大。 With Qt Designer:
使用Qt Designer:
I just tested the code below works for me: 我刚刚测试了下面的代码对我有用:
import sys
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, uic
uifilename = 'test.ui'
form_class = uic.loadUiType(uifilename)[0] #dirty reading of the ui file. better to convert it to a '.py'
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setupUi(self)
self.onInit()
def onInit(self):
#usually a lot of connections here
self.x_fit = np.linspace(1,10000, 10000)
self.y_fit = [f(_x) for _x in self.x_fit]
self.plotwidget.plot(self.x_fit,self.y_fit,symbol='o',pen=None)
self.plotwidget.setLabel('left',text='toto',units='')
self.plotwidget.setLabel('top',text='tata',units='')
def f(x):
return x**2+1
if __name__ == '__main__':
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
app = QtGui.QApplication([])
pg.setConfigOption('background', 'w')
win = MyWindowClass()
win.show()
app.exec_()
with this test.ui : https://github.com/steph2016/profiles/blob/master/test.ui . 使用此test.ui: https : //github.com/steph2016/profiles/blob/master/test.ui 。 Note the plotwidget is encapsulated inside a layout.
请注意,plotwidget封装在布局内。 I thought it works with just the Main Window, but I'm not sure anymore...
我以为它仅适用于主窗口,但我不确定...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.