简体   繁体   English

动态更新 matplotlib 图

[英]Updating a matplotlib graph dynamically

I am trying to dynamically update a matplotlib from a.txt file that periodically updates.我正在尝试从定期更新的.txt 文件动态更新 matplotlib。

For this, I used the following tutorial.为此,我使用了以下教程。

https://pythonprogramming.net/python-matplotlib-live-updating-graphs/ https://pythonprogramming.net/python-matplotlib-live-updating-graphs/

The.txt file looks like such The.txt 文件看起来像这样

1,2
2,3
3,6
4,9
5,4
6,7
7,7
8,4
9,3
10,10

The code looks like such:代码看起来像这样:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

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)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

This output a figure with these points plotted.这个 output 绘制了这些点的图形。

When I update with a new line, such as 11,15 , and save there is no updated figure.当我用新行更新时,例如11,15并保存,没有更新的数字。

How can I make this update to the current figure as a new line is added to the.txt file?当新行添加到 .txt 文件时,如何对当前图形进行此更新?

I have tried some of the solutions to these questions asked on stackoverflow without success:对于在 stackoverflow 上提出的这些问题,我已经尝试了一些解决方案但没有成功:

live updating with matplotlib 使用 matplotlib 实时更新

What is the currently correct way to dynamically update plots in Jupyter/iPython? 当前在 Jupyter/iPython 中动态更新绘图的正确方法是什么?

I created the code with the understanding that the intent of the question was to draw a graph based on the row-by-row data by retrieving the values from an updated, localized text file.我创建代码时理解问题的目的是通过从更新的本地化文本文件中检索值来基于逐行数据绘制图形。 The main points that I modified are the initial settings and updating the values in the animation function.我修改的要点是初始设置和更新animation function中的值。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
from matplotlib.animation import PillowWriter
#from IPython.display import HTML



pullData = open("sampleText.txt","r").read()
dataArray = pullData.split('\n')
frm = len(dataArray) 

fig = plt.figure()
ax1 = plt.axes(xlim=(0, size), ylim=(0, size))

line, = ax1.plot([],[], 'r-', lw=3)
xar = []
yar = []

def animate(i):
    if i < size:
        x,y = dataArray[i].split(',')
        xar.append(int(x))
        yar.append(int(y))
        line.set_data(xar, yar)
        ax1.set_ylim(0, max(yar)+3)
        return line


ani = animation.FuncAnimation(fig, animate, frames=frm, interval=200, repeat=False)
ani.save('plot_ani_test.gif', writer='pillow')
# jupyter lab 
# plt.close()
# HTML(ani.to_html5_video())

在此处输入图像描述

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

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