【问题标题】:Python - live update graphs; to plot Time on x-axisPython - 实时更新图;在 x 轴上绘制时间
【发布时间】:2016-02-01 09:00:21
【问题描述】:

我有一个 python 脚本,它以

的形式从服务器收集数据
<hh-mm-ss>,<ddd>

这里,第一个字段是日期,第二个字段是整数。此数据正在写入文件中。

我正在运行另一个线程,它正在从我在上一段中提到的文件中绘制实时图表。

所以这个文件有类似的数据,

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

现在我想用上面显示的数据绘制一个时间序列 Matplotlib 图。 但是当我尝试时,它会抛出一个错误提示,

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

当我有如下所示的正常数据时,一切都很好

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

更新 我从上面描述的文件生成图形的代码如下所示,

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)

更新代码

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)

现在我在这一行收到错误 (ax1.plot(xar,yar)) 我将如何克服这个问题?

【问题讨论】:

  • 您应该发布您的代码以展示您的尝试。尽管如此,我还是给你留下了一个回复,应该可以帮助你朝着正确的方向前进。
  • 我将发布我的代码,如果您出于这个原因这样做,请删除否决票。我只是在编辑我的问题:(
  • 完成..请撤消它。

标签: python matplotlib graph


【解决方案1】:

错误告诉您问题的原因:您正在尝试将字符串(例如'15:53:09')转换为整数。此字符串不是有效数字。

相反,您应该考虑使用 datetime 模块中的 datetime 对象来处理日期/时间事物,或者至少使用 split将字符串放入字段中,使用 ':' 作为分隔符并使用每个字段分开。

考虑这个简短的演示:

>>> 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'
>>>

【讨论】:

    【解决方案2】:

    您正试图从表示时间戳的字符串中解析整数。当然失败了。

    为了能够在绘图中使用时间戳,您需要将它们解析为正确的类型,例如 datetime.timedatetime.datetime。您可以为此使用datetime.datetime.strptime()dateutil.parser.parse()time.strptime()

    那么,绘制数据是直截了当的。看看交互式绘图模式:matplotlib.pyplot.ion()

    供参考/进一步阅读:


    根据您的代码,我创建了一个示例。我已经内联了一些注释,说明为什么我认为这样做会更好。

    # 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()
    

    进一步阅读:

    【讨论】:

    • 我现在收到这样的错误 "ValueError: invalid literal for float(): 19:09:12" 这里 19:09:12 是我想在 x 轴上显示的时间.我已经在我的问题中发布了更新的代码
    • @VasanthNagKV 您必须提供有关错误的更多信息(哪一行,哪个上下文?),以便它有用。但是,您似乎再次向xar 列表添加了一个字符串。那时不要打电话给strftime()。它将对象转换为字符串表示形式。你不想这样。
    • 我已经给了你我相信的所有信息。请让我知道一件事。可以使用日期时间对象在 xaxis 上绘图吗?还是应该是 int 或 float?
    • 在这一行出现错误 - x,y = zip(*data) "ValueError: need more than 0 values to unpack"
    • @VasanthNagKV 这意味着您的输入数据为空。那么你应该修复你的数据输入步骤。
    猜你喜欢
    • 2020-09-18
    • 2016-06-24
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    相关资源
    最近更新 更多