简体   繁体   中英

Matplotlib Embed a graph in to a UI PyQt5

I have a function in another script that draws a graph, so the graph is already predrawn, I just want to place it in to a widget on my interface in PyQt5. I have imported it, and when it runs it opens two windows, one with the graph in and one with the user interface in. Any ideas?

Here is the code:

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

This is in one script. In my GUI script, I have imported these:

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 *

And at the start of my window class, before the setup function, I have this function:

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

Instead of calling plt.show you need to place the figure that is produced by your imported script into the FigureCanvas of your PyQt GUI.

So in your plotting script do

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

In your GUI script use the figure obtained to place it into the canvas.

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


If you want to return an image, you can save it to a Byte buffer,

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

and then show it as image in the PyQt GUI. (I haven't tested the below, so it may work a bit differently.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM