我的終極整理,供參考
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# 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ū)ο?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 () |
總結(jié)就是,想要在特定的位置放matplotlib繪圖還是要用面向?qū)ο蟮腁PI,但混合使用pyplot的API可以使代碼更簡單。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/lemonade_117/article/details/103863357