您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)怎么在將matplotlib繪圖嵌入到pyqt中,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
# coding:utf-8 import matplotlib # 使用 matplotlib中的FigureCanvas (在使用 Qt5 Backends中 FigureCanvas繼承自QtWidgets.QWidget) from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtWidgets import QDialog, QPushButton, QVBoxLayout import matplotlib.pyplot as plt import numpy as np import sys """學(xué)好pyplot API和面向?qū)ο?nbsp;API搞定matplotlib繪圖顯示在GUI界面上""" class Main_window(QDialog): def __init__(self): super().__init__() # 三步走,定Figure,定Axes,定FigureCanvas # 1 直接一段代碼搞定figure和axes self.figure, (self.ax1, self.ax2) = plt.subplots(figsize=(13, 3), ncols=2) # 2 先創(chuàng)建figure再創(chuàng)建axes # 2.1 用plt.figure() / Figure() 創(chuàng)建figure, 推薦前者 self.figure = plt.figure(figsize=(5,3), facecolor='#FFD7C4') # self.figure = Figure(figsize=(5,3), facecolor='#FFD7C4') # 2.2 用plt.subplots() / plt.add_subplot() 創(chuàng)建axes, 推薦前者 (self.ax1, self.ax2) = self.figure.subplots(1, 2) # ax1 = self.figure.add_subplot(121) # ax2 = self.figure.add_subplot(122) # 3 綁定figure到canvas上 self.canvas = FigureCanvas(self.figure) self.button_draw = QPushButton("繪圖") self.button_draw.clicked.connect(self.Draw) # 設(shè)置布局 layout = QVBoxLayout() layout.addWidget(self.canvas) layout.addWidget(self.button_draw) self.setLayout(layout) def Draw(self): AgeList = ['10', '21', '12', '14', '25'] NameList = ['Tom', 'Jon', 'Alice', 'Mike', 'Mary'] # 將AgeList中的數(shù)據(jù)轉(zhuǎn)化為int類型 AgeList = list(map(int, AgeList)) # 將x,y轉(zhuǎn)化為numpy數(shù)據(jù)類型,對于matplotlib很重要 self.x = np.arange(len(NameList)) + 1 self.y = np.array(AgeList) # tick_label后邊跟x軸上的值,(可選選項(xiàng):color后面跟柱型的顏色,width后邊跟柱體的寬度) self.ax1.bar(range(len(NameList)), AgeList, tick_label=NameList, color='green', width=0.5) for a, b in zip(self.x, self.y): self.ax1.text(a-1, b, '%d' % b, ha='center', va='bottom') plt.title("Demo") pos = self.ax2.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r) self.figure.colorbar(pos, ax=self.ax2) # 終于可以用colorbar了 self.canvas.draw() # 運(yùn)行程序 if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) main_window = Main_window() main_window.show() app.exec()
看完上述內(nèi)容,你們對怎么在將matplotlib繪圖嵌入到pyqt中有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。