如何在 PyQt5 GUI python 中单击按钮时绘制方形图
Posted
技术标签:
【中文标题】如何在 PyQt5 GUI python 中单击按钮时绘制方形图【英文标题】:How to plot squarify graph on button click in PyQt5 GUI python 【发布时间】:2018-04-18 17:49:26 【问题描述】:我是 python 初学者,正在使用 PyQt5 创建 GUI,但遇到了问题,请帮忙。
这是一个方形图的例子
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()
这是我在单击按钮时调用的函数,它正在绘制随机图。
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()
如何在这个 GUI 上绘制方形图?
【问题讨论】:
【参考方案1】: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_())
【讨论】:
以上是关于如何在 PyQt5 GUI python 中单击按钮时绘制方形图的主要内容,如果未能解决你的问题,请参考以下文章
在pyqt5中退出GUI时终止正在运行的进程的正确方法是什么?