2017-04-18 129 views
2

我在matplotlib中创建了一个图表,并且希望将其添加到图像中并在我的pyqt5应用程序中使用它。有人建议我为此使用BytesIO。这是到目前为止我的代码:如何在matplotlib和pyqt5中使用BytesIO?

绘制图表中的数据:

... 
plt.axis('equal') 
buff = io.BytesIO() 
plt.savefig(buff, format="png") 
print(buff) 
return buff 

这被当时称为在另一个脚本:

def minionRatioGraphSetup(self, recentMinionRatioAvg): 
    image = minionRatioGraph(recentMinionRatioAvg) 
    label = QtWidgets.QLabel() 
    pixmap = QtGui.QPixmap(image) 
    label.setPixmap(pixmap) 
    label.setGeometry(QtCore.QRect(0,0,200,200)) 

它停在pixmap = QtGui.QPixmap(image)工作,我不确定为什么。另外:我怎么能把它放在我的主窗口?因为我怀疑那里的代码会工作大声笑

回答

1

我敢肯定有一个解决方案使用缓冲区。但是,要使字节格式正确,似乎相当复杂。因此,另一种方法是将图像保存到磁盘,然后从那里加载它。

import sys 
from PyQt4 import QtGui 
import matplotlib.pyplot as plt 
import numpy as np 

def minionRatioGraph(): 
    plt.plot([1,3,2]) 
    plt.savefig(__file__+".png", format="png") 


class App(QtGui.QWidget): 

    def __init__(self): 
     super(App, self).__init__() 
     self.setGeometry(300, 300, 250, 150) 
     self.setLayout(QtGui.QVBoxLayout()) 
     label = QtGui.QLabel() 
     label2 = QtGui.QLabel("Some other text label") 

     minionRatioGraph() 

     qimg = QtGui.QImage(__file__+".png") 
     pixmap = QtGui.QPixmap(qimg) 

     label.setPixmap(pixmap) 
     self.layout().addWidget(label) 
     self.layout().addWidget(label2) 
     self.show() 


if __name__ == '__main__': 
    app = QtGui.QApplication([]) 
    ex = App() 
    sys.exit(app.exec_()) 
+0

感谢的人,你是一个救星。我一直在用这个哈哈拉我的头发 –

0

使用枕头的一个片段,可能有助于避免文件IO

im = PIL.Image.open("filename") 
with BytesIO() as f: 
    im.save(f, format='png') 
    f.seek(0) 
    image_data = f.read() 
    qimg = QImage.fromData(image_data) 
    patch_qt = QPixmap.fromImage(qimg)