2017-04-18 126 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)