How to plot squarify graph on button click in PyQt5 GUI python

时间:2018-04-18 17:49:27

标签: python matplotlib pyqt pyqt5 squarify

I am a python beginner and am creating a GUI using PyQt5 and have run into a problem, please help.

This is a squarify graph's example

import pandas as pd
df = pd.DataFrame({'nb_people':[8,3,4,2], 'group':["group A", "group B", 
"group C", "group D"] })
squarify.plot(sizes=df['nb_people'], label=df['group'], alpha=.8 )
plt.axis('off')
plt.show()

And this is a function that I'm calling on button click which is plotting a random graph.

def plot(self):

    # random data
    data = [random.random() for i in range(10)]

    # instead of ax.hold(False)
    self.figure.clear()

    # create an axis
    ax = self.figure.add_subplot(111)

    # plot data
    ax.plot(data, '*-')

    # refresh canvas
    self.canvas.draw()

How to plot that squarify graph on this GUI?

1 个答案:

答案 0 :(得分:2)

squarify.plot()有一个名为ax的参数,它是绘制它的轴。

import sys
import random
import pandas as pd

import matplotlib
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import squarify

class Widget(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        QtWidgets.QWidget.__init__(self, *args, **kwargs)
        self.figure = Figure(figsize=(5, 4), dpi=100)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)

        button = QtWidgets.QPushButton("random plot")
        button.clicked.connect(self.plot)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.canvas)
        lay.addWidget(button)
        self.plot()

    def plot(self):
        self.figure.clear()
        df = pd.DataFrame({'nb_people':[random.randint(1, 10) for i in range(4)], 'group':["group A", "group B", "group C", "group D"] })
        ax = self.figure.add_subplot(111)
        squarify.plot(sizes=df['nb_people'], label=df['group'], alpha=.8 ,ax=ax)
        ax.axis('off')
        self.canvas.draw()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

enter image description here