简体   繁体   English

Python - 实时更新图; 在 x 轴上绘制时间

[英]Python - live update graphs; to plot Time on x-axis

i have a python script that collects data from a server in the form of我有一个 python 脚本,它以以下形式从服务器收集数据

<hh-mm-ss>,<ddd>

here, the first field is Date and the second field is an integer digit.在这里,第一个字段是日期,第二个字段是一个整数。 this data is being written into a file.此数据正在写入文件中。

i have another thread running which is plotting a live graph from the file which i mentioned in the above paragraph.我有另一个线程正在运行,它正在从我在上一段中提到的文件中绘制实时图形。

so this file has data like,所以这个文件有这样的数据,

<hh-mm-ss>,<ddd>
<hh-mm-ss>,<ddd>
<hh-mm-ss>,<ddd>
<hh-mm-ss>,<ddd>

Now i want to plot a time series Matplotlib graph with the above shown data.现在我想用上面显示的数据绘制一个时间序列 Matplotlib 图。 but when i try , it throws an error saying,但是当我尝试时,它会抛出一个错误说,

ValueError: invalid literal for int() with base 10: '15:53:09'

when i have normal data like shown below, things are fine当我有如下所示的正常数据时,一切都很好

<ddd>,<ddd>
<ddd>,<ddd>
<ddd>,<ddd>
<ddd>,<ddd>

UPDATE my code that generates graph from the file i have described above is shown below,更新我从上面描述的文件生成图形的代码如下所示,

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)

UPDATED CODE更新代码

def animate(i):
    print("inside animate")
    pullData = open("sampleText.txt","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            timeX=datetime.strptime(x, "%H:%M:%S")
            xar.append(timeX.strftime("%H:%M:%S"))
            yar.append(float(y))
    ax1.clear()
    ax1.plot(xar,yar)

Now i am getting the error at this line ( ax1.plot(xar,yar) ) how will i get over this?现在我在这一行收到错误( ax1.plot(xar,yar) )我将如何克服这个问题?

You are trying to parse an integer from a string representing a timestamp.您正在尝试从表示时间戳的字符串中解析一个整数。 Of course it fails.当然失败了。

In order to be able to use the timestamps in a plot, you need to parse them to the proper type, eg, datetime.time or datetime.datetime .为了能够在绘图中使用时间戳,您需要将它们解析为正确的类型,例如datetime.timedatetime.datetime You can use datetime.datetime.strptime() , dateutil.parser.parse() or maybe also time.strptime() for this.您可以dateutil.parser.parse()使用datetime.datetime.strptime()dateutil.parser.parse()time.strptime()

Plotting the data is straight-forward, then.那么,绘制数据是直截了当的。 Have a look at the interactive plotting mode: matplotlib.pyplot.ion() .看看交互式绘图模式: matplotlib.pyplot.ion()

For reference/further reading:供参考/进一步阅读:


Based on your code I have created an example.根据您的代码,我创建了一个示例。 I have inlined some notes as to why I think it's better to do it this way.我已经内联了一些关于为什么我认为这样做更好的注释。

# use with-statement to make sure the file is eventually closed
with open("sampleText.txt") as f:
    data = []
    # iterate the file using the file object's iterator interface
    for line in f:
        try:
            t, f = line.split(",")
            # parse timestamp and number and append it to data list
            data.append((datetime.strptime(t, "%H:%M:%S"), float(f)))
        except ValueError:
            # something went wrong: inspect later and continue for now
            print "failed to parse line:", line
# split columns to separate variables
x,y = zip(*data)
# plot
plt.plot(x,y)
plt.show()
plt.close()

For further reading:进一步阅读:

The error tells you the cause of the problem: You're trying to convert a string, such as '15:53:09' , into an integer.该错误告诉您问题的原因:您正在尝试将字符串(例如'15:53:09' )转换为整数。 This string is not a valid number.此字符串不是有效数字。

Instead, you should either look into using a datetime object from the datetime module to work with date/time things or at least split ting the string into fields using ':' as the delimiter and the using each field separately.相反,您应该考虑使用datetime模块中的datetime对象来处理日期/时间事物,或者至少split字符串split为使用':'作为分隔符并分别使用每个字段的字段。

Consider this brief demo:考虑这个简短的演示:

>>> time = '15:53:09'
>>> time.split(':')
['15', '53', '09']
>>> [int(v) for v in time.split(':')]
[15, 53, 9]
>>> int(time)  # expect exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '15:53:09'
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM