简体   繁体   English

Matplotlib FuncAnimation 未按顺序绘制 x 轴

[英]Matplotlib FuncAnimation not plotting x-axis in order

I'm trying to grab data from a text file and plot it using the animation.FuncAnimation module from matplotlib.我正在尝试从文本文件中获取数据并使用 matplotlib 中的 animation.FuncAnimation 模块绘制它。 Here is my code that I'm trying to make run correctly这是我试图正确运行的代码

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use('ggplot')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    graph_data = open('example.txt', 'r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:
        x,y = line.split(',')
        xs.append(x)
        ys.append(y)

    ax1.clear()
    ax1.plot(xs, ys)

animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

example.txt is an 18-line text file (omitted for space reasons) which contain (x,y) pairs of data which I'd like to plot. example.txt 是一个 18 行的文本文件(由于空间原因省略),其中包含我想要绘制的 (x,y) 对数据。 However, matplotlib is not plotting the x values in order: once they reach 10, they 'wrap around' back to the beginning, sandwiching themselves between 1 and 2. Makes for a pretty bad graph.然而,matplotlib 并没有按顺序绘制 x 值:一旦它们达到 10,它们就会“绕回”回到开头,将自己夹在 1 和 2 之间。导致了一个非常糟糕的图表。

I'm having some trouble figuring out what's wrong with my implementation.我在弄清楚我的实现有什么问题时遇到了一些麻烦。 I've even tried sorting the values before plotting them, but the plot still comes out like this .我什至尝试在绘制之前对值进行排序,但情节仍然是这样的

All help is appreciated!感谢所有帮助! I've been scouring doc pages and StackOverflow for a while now, and I can't seem to find anyone whose had this same problem.我已经搜索文档页面和 StackOverflow 一段时间了,我似乎找不到任何有同样问题的人。

Quick answer: Working example below.快速回答:下面的工作示例。

There are few aspects you should be aware of.您应该注意几个方面。 Firstly, FuncAnimation will execute animate function on each call, ie every interval milliseconds, which in your case is 1 second.首先, FuncAnimation将在每次调用时执行animate函数,即每interval毫秒,在您的情况下为 1 秒。 You don't really want to read file again and again... do it once before and then update your view.你真的不想一次又一次地阅读文件......之前做一次然后更新你的视图。 Secondly, creating each time whole axis (ax.plot) is very expensive and it'll slow down quickly.其次,每次创建整个轴(ax.plot)非常昂贵,而且速度会很快变慢。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style


graph_data = open('example.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []

for line in lines[:-1]:
    x,y = line.split(',')
    xs.append(float(x))
    ys.append(float(y))

# This is where you want to sort your data
# sort(x, y, reference=x) # no such function

style.use('ggplot')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

x, y = [], [] # Prepare placeholders for animated data
ln, = plt.plot(x, y, animated=True)
ax1.set_xlim(min(xs), max(xs)) # Set xlim in advance
ax1.set_ylim(min(ys), max(ys)) #     ylim

def animate(i):
    x.append(xs[i])
    y.append(ys[i])
    ln.set_data(x, y)
    return ln,

ani = animation.FuncAnimation(fig, animate, frames=range(len(xs)),  
                                interval=1000, repeat=False, blit=True)
plt.show()

Notice that we used repeat flag to False.请注意,我们使用repeat标志为 False。 This means that once it goes through whole frames list then it stops.这意味着一旦它遍历了整个frames列表,它就会停止。

The numbers are not in order because you are treating them as strings not numbers.数字没有顺序,因为您将它们视为字符串而不是数字。 So append them as floats and it will solve it.所以将它们附加为浮点数,它会解决它。 Try:尝试:

xs.append(float(x))
ys.append(float(y))

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

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