【问题标题】:Python - live graph update from a changing text filePython - 来自不断变化的文本文件的实时图形更新
【发布时间】:2016-02-01 02:55:12
【问题描述】:

我有一个线程每 2 秒连续写入一个文本文件。 Matplotlib 图(实时更新图)引用了相同的文件。

所以当我启动脚本时,我会打开一个图表并在一个线程上启动文件写入过程。该文件正在更新,但不是我的图表。只有在文件写入完成后,文件上的数据才会显示在图表上。

但这不是实时图表的概念。我希望数据表示在数据写入文件时显示。我在这里做错了什么?

这是我的主要功能

def Main():
    t1=Thread(target=FileWriter)
    t1.start()
    ani = animation.FuncAnimation(fig, animate, interval=1000)
    plt.show()
    print("done")

我的文件写入函数

def FileWriter():
    f=open('F:\\home\\WorkSpace\\FIrstPyProject\\TestModules\\sampleText.txt','w')
    k=0
    i=0
    while (k < 20):
        i+=1
        j=randint(10,19)
        data = f.write(str(i)+','+str(j)+'\n')
        print("wrote data")
        time.sleep(2)
        k += 1

我的图表功能

def animate(i):
    pullData = open("sampleText.txt","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax1.clear()
    ax1.plot(xar,yar)

【问题讨论】:

    标签: python matplotlib graph


    【解决方案1】:

    该问题与 matplotlib 无关,而与您如何将数据读取和写入文本文件有关。

    Python file objects are usually line-buffered by default,因此当您从FileWriter 线程内部调用f.write(str(i)+','+str(j)+'\n') 时,您的文本文件不会立即在磁盘上更新。因此,open("sampleText.txt","r").read() 返回一个空字符串,因此您没有要绘制的数据。

    要强制“立即”更新文本文件,您可以在写入文件后立即调用f.flush(),或者您可以在打开文件时将缓冲区大小设置为零,例如f = open('sampleText.txt', 'w', 0)(也可以查看previous SO question)。

    【讨论】:

      【解决方案2】:

      自发布以来已经有几年了,但我正在处理这个问题,我遇到了一个问题,我需要在每个周期后更新图表。

      我尝试使用 ali_m 的建议:f=open('./dynamicgraph.txt','a', 0),但是缓冲“无法设置为 0”时出错。

      如果你在 FileWriter 的 while 循环中加入一个 flush() 函数,它会在每个循环后更新图形。这是程序的完整代码,它将在运行时绘制图形:

      #!usr/bin/python3
      import matplotlib.pyplot as plt
      import matplotlib.animation as animation
      import time
      from random import randrange
      from threading import Thread
      
      fig = plt.figure()
      ax1 = fig.add_subplot(1,1,1)
      
      
      def FileWriter():
          f=open('./dynamicgraph.txt','a')
          i=0
          while True:
              i+=1
              j=randrange(10)
              data = f.write(str(i)+','+str(j)+'\n')
              print("wrote data")
              time.sleep(1)
              f.flush()
      
      
      def animate(i):
          pullData = open("dynamicgraph.txt","r").read()
          dataArray = pullData.split('\n')
          xar = []
          yar = []
          for eachLine in dataArray:
              if len(eachLine)>1:
                  x,y = eachLine.split(',')
                  xar.append(int(x))
                  yar.append(int(y))
          ax1.clear()
          ax1.plot(xar,yar)
      
      def Main():
          t1=Thread(target=FileWriter)
          t1.start()
          ani = animation.FuncAnimation(fig, animate, interval=1000)
          plt.show()
          print("done")
      
      Main()
      

      【讨论】:

        猜你喜欢
        • 2021-08-20
        • 2013-10-20
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 2015-03-21
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        相关资源
        最近更新 更多