animation模块的使用

1.动画的实现—初探

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-', animated=False)

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

2.结合pyqt

from PyQt5.QtWidgets import QPushButton,QWidget,QApplication,QGridLayout,QListWidget,QLineEdit

import pyqtgraph as pg
# pyqtgraph使用matplotlib
import pyqtgraph.widgets.MatplotlibWidget as mw
import sys
import numpy as np

# 用于中文乱码
import matplotlib
""" 绘图防止乱码 """
# 指定默认字体 下面三条代码用来解决绘图中出现的乱码
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family'] = 'sans-serif'
# 解决负号'-'显示为方块的问题
matplotlib.rcParams['axes.unicode_minus'] = False

from matplotlib.animation import FuncAnimation

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()


    def initUI(self):
        self.setGeometry(50,50,800,620)
        self.setWindowTitle("animation动画—结合pyqt")

        model_plt = mw.MatplotlibWidget()
        # 隐藏matplotlib中的工具栏
        model_plt.toolbar.setVisible(False)
        self.fig = model_plt.getFigure()
        # 设置一个1*1面板
        self.ax = self.fig.add_subplot(111)

        self.xdata, self.ydata = [], []
        self.ln, = self.ax.plot([], [], 'r-', animated=False)

        ani = FuncAnimation(self.fig, self.update, frames=np.linspace(0, 2 * np.pi, 128),
                            init_func=self.init, blit=True)



        self.gridLayout = QGridLayout(self)
        ## 将部件添加到布局中的适当位置
        self.gridLayout.addWidget(model_plt, 0, 0)

    def init(self):
        self.ax.set_xlim(0, 2 * np.pi)
        self.ax.set_ylim(-1, 1)
        return self.ln,

    def update(self, frame):
        self.xdata.append(frame)
        self.ydata.append(np.sin(frame))
        self.ln.set_data(self.xdata, self.ydata)
        return self.ln,


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())


posted on 2019-07-18 21:22  小明他很忙  阅读(583)  评论(0编辑  收藏  举报

导航