基于动态值在Matplotlib中更新轴

时间:2016-08-02 14:03:36

标签: python linux matplotlib plot graph

我正在开发一个项目,在该项目中,我从文本文件中读取值,该文件文件使用由空格分隔的两个值进行动态更新。将这些值放入列表中,然后绘制两个值,每个值都是y轴上的点,时间是x轴。在下面提供的第一组代码中,我可以接收值并绘制它们,然后将该图保存为png。但是,随着更多数据的出现,图表似乎不会更新时间值。但图表确实反映了值的变化。

 # -*- coding: utf-8 -*-
"""
Created on Mon Jul 25 11:23:14 2016

@author: aruth3
"""

import matplotlib.pyplot as plt
import sys
import time
import datetime

class reader():
    """Reads in a comma seperated txt file and stores the two strings in two variables"""

    def __init__(self, file_path):
        """Initialize Reader Class"""
        self.file_path = file_path

    # Read File store in f -- Change the file to your file path
    def read_file(self):
        """Reads in opens file, then stores it into file_string as a string"""
        f = open(self.file_path)
        # Read f, stores string in x
        self.file_string = f.read()

    def split_string(self):
        """Splits file_string into two variables and then prints them"""
        # Splits string into two variables
        try:
            self.val1, self.val2 = self.file_string.split(' ', 1)
        except ValueError:
            print('Must Have Two Values Seperated By a Space in the .txt!!')
            sys.exit('Terminating Program -- Contact Austin')
        #print(val1)  # This is where you could store each into a column on the mysql server
        #print(val2)

    def getVal1(self):
            return self.val1

    def getVal2(self):
            return self.val2

read = reader('testFile.txt')
run = True
tempList = []
humList = []
numList = [] # Represents 2 Secs
my_xticks = []
i = 0

while(run):
    plt.ion()
    read.read_file()
    read.split_string()
    tempList.append(read.getVal1())
    humList.append(read.getVal2())
    numList.append(i)
    i = i + 1
    my_xticks.append(datetime.datetime.now().strftime('%I:%M'))
    plt.ylim(0,125)
    plt.xticks(numList,my_xticks)
    plt.locator_params(axis='x',nbins=4)
    plt.plot(numList,tempList, 'r', numList, humList, 'k')
    plt.savefig('plot.png')
    time.sleep(10) # Runs every 2 seconds

testFile.txt有两个值100 90,可以动态更新并在图表中更改。但随着时间的推移,你会注意到(如果你运行代码)时间没有更新。

要解决时间不更新问题,我认为使用pop修改列表会允许第一个值离开,然后在循环时返回另一个值。就更新时间而言,这有效,但最终搞砸了图表: Link To Bad Graph Image

代码:

# -*- coding: utf-8 -*-
"""
Created on Tue Aug  2 09:42:16 2016

@author: aruth3
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Jul 25 11:23:14 2016

@author:
"""

import matplotlib.pyplot as plt
import sys
import time
import datetime

class reader():
    """Reads in a comma seperated txt file and stores the two strings in two variables"""

    def __init__(self, file_path):
        """Initialize Reader Class"""
        self.file_path = file_path

    # Read File store in f -- Change the file to your file path
    def read_file(self):
        """Reads in opens file, then stores it into file_string as a string"""
        f = open(self.file_path)
        # Read f, stores string in x
        self.file_string = f.read()

    def split_string(self):
        """Splits file_string into two variables and then prints them"""
        # Splits string into two variables
        try:
            self.val1, self.val2 = self.file_string.split(' ', 1)
        except ValueError:
            print('Must Have Two Values Seperated By a Space in the .txt!!')
            sys.exit('Terminating Program -- Contact')
        #print(val1)  # This is where you could store each into a column on the mysql server
        #print(val2)

    def getVal1(self):
            return self.val1

    def getVal2(self):
            return self.val2

read = reader('testFile.txt')
run = True
tempList = []
humList = []
numList = [] # Represents 2 Secs
my_xticks = []
i = 0
n = 0 # DEBUG

while(run):
    plt.ion()
    read.read_file()
    read.split_string()
    if n == 4:
        my_xticks.pop(0)
        tempList.pop(0)
        humList.pop(0)
        numList = [0,1,2]
        i = 3
        n = 3
    tempList.append(read.getVal1())
    humList.append(read.getVal2())
    numList.append(i)
    i = i + 1
    my_xticks.append(datetime.datetime.now().strftime('%I:%M:%S')) # Added seconds for debug
    plt.ylim(0,125)
    plt.xticks(numList,my_xticks)
    plt.locator_params(axis='x',nbins=4)
    plt.plot(numList,tempList, 'r', numList, humList, 'k')
    plt.savefig('plot.png')
    time.sleep(10) # Runs every 2 seconds
    n = n + 1
    print(n) # DEBUG
    print(numList)# DEBUG
    print('-------')# DEBUG
    print(my_xticks)# DEBUG
    print('-------')# DEBUG
    print(tempList)# DEBUG
    print('-------')# DEBUG
    print(humList)# DEBUG

所以我的问题是如何创建一个图表,当新值出现时,它会激活列表中的第一个值,从而更新时间,但是也可以提供精确的数据图表而不会出现故障?

列表中的弹出似乎是一个好主意,但我不确定为什么它会弄乱图表?

谢谢!

1 个答案:

答案 0 :(得分:0)

这个问题在https://codereview.stackexchange.com/

可能更合适

伪代码

plotData = []
for (1 to desired size)
  plotData[i] = 0

 while data
   update time
   plotData.push(data with time)
   plotData.popTop(oldest data)
   Draw plotData
 end while