前段时间写程序,要在PyQt5中插入统计图,在网上查了很多资料,这里整理一下。
源码
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
| import matplotlib
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
class Main_window(QDialog): def __init__(self): super().__init__()
self.figure = plt.figure(facecolor='#FFD7C4') self.canvas = FigureCanvas(self.figure) self.button_draw = QPushButton("绘图")
self.button_draw.clicked.connect(self.Draw)
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 = list(map(int, AgeList))
self.x = np.arange(len(NameList)) + 1 self.y = np.array(AgeList)
plt.bar(range(len(NameList)), AgeList, tick_label=NameList, color='green', width=0.5)
for a, b in zip(self.x, self.y): plt.text(a-1, b, '%d' % b, ha='center', va='bottom')
plt.title("Demo") self.canvas.draw() plt.savefig('1.jpg')
if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) main_window = Main_window() main_window.show() app.exec()
|