繁体   English   中英

Matplotlib FuncAnimation 未按顺序绘制 x 轴

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

我正在尝试从文本文件中获取数据并使用 matplotlib 中的 animation.FuncAnimation 模块绘制它。 这是我试图正确运行的代码

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 是一个 18 行的文本文件(由于空间原因省略),其中包含我想要绘制的 (x,y) 对数据。 然而,matplotlib 并没有按顺序绘制 x 值:一旦它们达到 10,它们就会“绕回”回到开头,将自己夹在 1 和 2 之间。导致了一个非常糟糕的图表。

我在弄清楚我的实现有什么问题时遇到了一些麻烦。 我什至尝试在绘制之前对值进行排序,但情节仍然是这样的

感谢所有帮助! 我已经搜索文档页面和 StackOverflow 一段时间了,我似乎找不到任何有同样问题的人。

快速回答:下面的工作示例。

您应该注意几个方面。 首先, FuncAnimation将在每次调用时执行animate函数,即每interval毫秒,在您的情况下为 1 秒。 你真的不想一次又一次地阅读文件......之前做一次然后更新你的视图。 其次,每次创建整个轴(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()

请注意,我们使用repeat标志为 False。 这意味着一旦它遍历了整个frames列表,它就会停止。

数字没有顺序,因为您将它们视为字符串而不是数字。 所以将它们附加为浮点数,它会解决它。 尝试:

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

暂无
暂无

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

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