如何使用带有matplotlib和pyqt5的BytesIO? [英] How to use BytesIO with matplotlib and pyqt5?

查看:464
本文介绍了如何使用带有matplotlib和pyqt5的BytesIO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made a graph in matplotlib, and wanted to make it in to an image and use it in my pyqt5 application. Someone suggested I use BytesIO for this. This is my code so far:

绘制我的图表:

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

然后在另一个脚本中调用它:

This is then called in another script:

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)工作,我不确定为什么。另外:我怎么能把它放在我的MainWindow?因为我怀疑代码会工作lol

It stops working at pixmap = QtGui.QPixmap(image) and I'm unsure why. Also: How could I place this in my MainWindow? because I doubt the code there will work lol

推荐答案

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

I'm sure there is a solution using a buffer. However, it seems rather complicated to get the byte format correct. So an alternative is to save the image to disk, and then load it from there.

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_())

这篇关于如何使用带有matplotlib和pyqt5的BytesIO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆