Shreyash Sharma
Shreyash Sharma

Reputation: 318

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

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?

Upvotes: 0

Views: 1587

Answers (1)

eyllanesc
eyllanesc

Reputation: 244033

squarify.plot() has an argument called ax which is the axes where it will be drawn.

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

Upvotes: 2

Related Questions