Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:保持实时绘图中的点数_Python_File_Matplotlib - Fatal编程技术网

Python:保持实时绘图中的点数

Python:保持实时绘图中的点数,python,file,matplotlib,Python,File,Matplotlib,我一直在尝试通过matplotlib创建一个实时绘图 我的试用码是这个 import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import time from PySide import QtCore fig = plt.figure() ax = fig.add_subplot(1,1,1) N=100 def animate(j): graph_da

我一直在尝试通过matplotlib创建一个实时绘图

我的试用码是这个

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import time
from PySide import QtCore

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

N=100

def animate(j):
    graph_data = open('example.txt','r').read()
    lines = graph_data.split('\n')
    xs=[]
    ys=[]

    for line in lines:
        if len(line) > 1:
            x,y = line.split(',')
            xs.append(float(x))
            ys.append(float(y))
    ax.clear()
    ax.plot(xs, ys)

def initFile():
    fid = open('example.txt','w')
    fid.write('')
    fid.close()
    for i in range(0,N):
        fid = open('example.txt', 'a')
        fid.write(str(i) + ',' + str(0) + '\n')
        fid.close()


def updateFile():
    global wThread
    wThread = writeThread()
    wThread.start()


class writeThread(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.exiting = False

    def run(self):
        i=0
        while 1:
            fid = open('example.txt', 'a')
            fid.write(str(N+i) + ',' + str(np.sin(2*np.pi*0.05*i)) + '\n')
            time.sleep(0.1)
            i=i+1
            fid.close()

initFile()
updateFile()
ani = animation.FuncAnimation(fig, animate, interval = 200)
plt.show()
它工作得很好。但是,绘图点是累积的。我想保持绘图中的点数为N


我该怎么做呢?

只需将数组/列表的大小限制在最后N个点:

def animate(j):
    (...)
    ax.clear()
    ax.plot(xs[-N:], ys[-N:])

这是一种方式。但我想将数据文件更新为N行。