Matplotlib FuncAnimation没有按顺序绘制x轴

时间:2017-11-20 02:02:48

标签: python matplotlib

我正在尝试从文本文件中获取数据并使用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之间。这会产生一个非常糟糕的图形。

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

感谢所有帮助!我一直在搜索doc pages和StackOverflow一段时间了,我似乎找不到任何有这个问题的人。

2 个答案:

答案 0 :(得分:0)

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

您应该注意几个方面。 首先,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列表,它就会停止。

答案 1 :(得分:-2)

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

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