Matplotlib将图形嵌入到UI PyQt5中

时间:2017-04-18 16:00:37

标签: python matplotlib pyqt5

我在另一个绘制图形的脚本中有一个函数,所以图形已经预先绘制了,我只想将它放在PyQt5中我界面上的一个小部件中。我已经导入了它,当它运行时它会打开两个窗口,一个带有图形,一个带有用户界面。任何想法?

以下是代码:

def minionRatioGraph(recentMinionRatioAvg):
    x = recentMinionRatioAvg
    a = x*10
    b = 100-a
    sizes = [a, b]
    colors = ['#0047ab', 'lightcoral']
    plt.pie(sizes, colors=colors)

    #determine score colour as scolour
    if x < 5:
       scolour = "#ff6961" #red
    elif 5 <= x < 5.5:
       scolour = "#ffb347" #orange
    elif 5.5 <= x < 6.5:
       scolour = "#77dd77" #light green
    elif 6.5 <= x:
       scolour = "#03c03c" # dark green

    #draw a circle at the center of pie to make it look like a donut
    centre_circle = plt.Circle((0,0),0.75, fc=scolour,linewidth=1.25)
    fig = plt.gcf()
    fig.gca().add_artist(centre_circle)

    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.show()

这是一个脚本。在我的GUI脚本中,我导入了这些:

from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as 
FigureCanvas
from graphSetup import *

在我的窗口类的开头,在setup函数之前,我有这个函数:

def minionGraphSetup(self, recentMinionRatioAvg):
    minionRatioGraph(recentMinionRatioAvg)

1 个答案:

答案 0 :(得分:0)

您需要将导入脚本生成的图形放入PyQt GUI的FigureCanvas中,而不是调用plt.show

所以在你的绘图剧本中

def minionRatioGraph(recentMinionRatioAvg):
    ...
    fig = plt.gcf()
    fig.gca().add_artist(centre_circle)
    plt.axis('equal')
    #plt.show() <- don't show window!
    return fig

在GUI脚本中,使用获得的图形将其放入画布中。

def minionGraphSetup(self, recentMinionRatioAvg):
    fig = minionRatioGraph(recentMinionRatioAvg)
    ...
    self.canvas = FigureCanvas(fig, ...)

<小时/> 如果要返回图像,可以将其保存到字节缓冲区

import io
def minionRatioGraph(recentMinionRatioAvg):
    ...
    fig = plt.gcf()
    fig.gca().add_artist(centre_circle)
    plt.axis('equal')
    buff = io.BytesIO()
    plt.savefig(buff, format="png")
    return buff

然后在PyQt GUI中将其显示为图像。 (我还没有对下面的内容进行测试,所以它可能会有所不同。)

def minionGraphSetup(self, recentMinionRatioAvg):
    image = minionRatioGraph(recentMinionRatioAvg)
    label = QLabel() 
    pixmap = QPixmap(image)
    label.setPixmap(pixmap)