【问题标题】:Python3x + MatPlotLib - Updating a chart?Python3x + MatPlotLib - 更新图表?
【发布时间】:2014-06-02 20:46:28
【问题描述】:

我是 python 和 matplotlib 语言的新手,正在为我丈夫做一些事情。

希望大家能帮帮我。

我想使用 Open 拉入一个文件,读取它,并用它的值更新一个图表。

听起来很简单吧?在实践中并没有那么多。

这是我到目前为止打开文件并绘制图表的内容。这可以正常工作,因为它可以将文件绘制 1 次。

import matplotlib.pyplot as plt
fileopen = open('.../plotresults.txt', 'r').read()
fileopen = eval(fileopen) ##because the file contains a dict and security is not an issue.
print(fileopen)  ## So I can see it working
for key,value in fileopen.items():
    plot1 = value
    plt.plot(plot1, label=str(key))
plt.legend()
plt.show()

现在我想为图表制作动画或更新它,以便我可以看到数据的变化。我曾尝试使用 matplotlib 的动画功能,但它超出了我目前的知识范围。

有没有一种简单的方法来更新这个图表,比如每 5 分钟一次?

注意: 我尝试使用 Schedule,但它破坏了程序(可能是 schedule 和 matplotlib 图形打开之间的冲突??)。

任何帮助将不胜感激。

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

    不幸的是,使用 matplotlib 的动画功能或 使用 matplotlib OO 界面,您只会浪费时间尝试获得干净的解决方案。

    作为一个肮脏的黑客,你可以使用以下内容:

    from threading import Timer
    
    from matplotlib import pyplot as plt
    import numpy
    
    # Your data generating code here
    def get_data():
        data = numpy.random.random(100)
        label = str(data[0]) # dummy label
        return data, label
    
    def update():
        print('update')
        plt.clf()
        data, label = get_data()
        plt.plot(data, label=label)
        plt.legend()
        plt.draw()
        t = Timer(0.5, update) # restart update in 0.5 seconds
        t.start()
    
    update()
    plt.show()
    

    它由Timer 衍生出第二个线程。所以要杀死脚本,你必须在控制台上敲两次Ctrl-C

    如果在pyplot 机器的范围内有一种更简洁的方法以这种简单的方式执行此操作,我自己会很感兴趣

    斜体编辑。

    【讨论】:

    • 最好是显式获取Axes对象的引用和我们的OO接口,而不是依赖pyplot状态机。
    • 这个例子将检查使用pyplot 机器可以走多远。关于OO接口:向线程开启者解释:)。编辑了我的答案。
    猜你喜欢
    • 2012-10-17
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2023-02-13
    • 2020-12-28
    • 2012-03-18
    • 1970-01-01
    相关资源
    最近更新 更多