首页 > 解决方案 > 为什么这个实时数据代码在 Google Colab 中不起作用?

问题描述

我对以下代码有疑问,该代码预计会在每次更新名为“example”的文本文件时显示一个 2D 图形。当您在 Google Colab 中运行它时,它在运行时没有任何错误显示。

您的帮助将不胜感激:)

[1] from google.colab import drive
    drive.mount('/content/drive')


[2] import time
    import matplotlib.pyplot as plt

[3] %matplotlib notebook
    plt.rcParams['animation.html'] = 'jshtml'

[4] fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.show()

[5] x, y = [], []
    leng1 = 0
    i = 0

    while True:
         pullData = open('/content/drive/My Drive/Colab Notebooks/example.txt', 'r').read()
         leng2 = len(pullData)
         pullData = pullData[leng1:leng2]
         leng1 = leng2
         dataArray = pullData.split('\n')
         for eachLine in dataArray:
             if len(eachLine)>1:
                 xar,yar = eachLine.split(',')
                 x.append(int(xar))
                 y.append(float(yar))

         ax.plot(x, y, color='b')

         fig.canvas.draw()

         ax.set_xlim(left=max(0, i - 50), right=i + 50)
         fig.show()
         plt.pause(0.05)
         i += 1

标签: pythonmatplotlibgraphgoogle-colaboratoryreal-time

解决方案


推荐阅读