1、在Qt designer中设计界面,包含一个QGroupBox和QWidget:
2、导入需要的库:
import matplotlib
matplotlib.use("Qt5Agg") # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
3、编写绘图函数:
def plot_figure(self, ax):
# 设置图表标题、轴名称等属性
ax.set_title("cos(x)")
ax.set_xlabel("x")
ax.set_ylabel("y")
# 生成数据
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2 * np.pi * x)
# 绘制曲线
ax.plot(x, y)
return ax
4、创建figure, canvas,绘制图表并显示至pyqt主界面:
# 创建figure
figure = plt.figure(figsize=(5, 3))
# 创建axes
ax = figure.subplots(1, 1)
# 或者一步直接创建figure和axes
# figure, ax = plt.subplots(figsize=(5, 3), ncols=1)
# 绑定figure到canvas上
canvas = FigureCanvas(figure)
# 绘图
ax = self.plot_figure(ax)
# 更新canvas画布
canvas.draw()
# 显示至pyqt主界面
self.gridlayout = QGridLayout(self.groupBox_name) # GroupBox的name
self.gridlayout.addWidget(canvas)
参考文章:
https://www.pianshen.com/article/2880262698/
https://blog.csdn.net/panrenlong/article/details/80183519
https://www.yht7.com/news/15932
Juliet 于2021.02