2016-08-02 1 views
0

Я работаю над проектом, в котором я читаю значения из текстового файла, который динамически обновляется с двумя значениями, разделенными пробелом. Эти значения берутся в список, а затем оба строятся с каждой точкой на оси y, а время - на оси x. В первом наборе кода, представленном ниже, я могу взять значения и построить их, а затем сохранить этот сюжет как png. Тем не менее, график, похоже, не обновляет значения времени по мере поступления большего количества данных. Но график отражает изменения значений.Обновление оси в Matplotlib на основе динамических значений

# -*- 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 

Так что мой вопрос, как я могу создать график, что, когда новые значения приходят в нем выдает первое значение в списке, тем самым обновляя время, но также предоставляет точный график данных без скрещивания?

Выпадающий список кажется хорошей идеей, но я не уверен, почему он испортил график?

Спасибо!

ответ

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