在matplotlib中对茎图进行动画处理 [英] animating a stem plot in matplotlib

查看:131
本文介绍了在matplotlib中对茎图进行动画处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在matplotlib中对茎图进行动画处理,但找不到所需的文档来帮助我.我有一系列数据文件,每个文件看起来都像这样:

I'm trying to animate a stem plot in matplotlib and I can't find the necessary documentation to help me. I have a series of data files which each look like this:

1 0.345346
2 0.124325
3 0.534585

我想将每个文件绘制为单独的框架.

and I want plot each file as a separate frame.

根据

According to this and this other tutorial, I should create a function which updates the data contained in each plot object (artist? I'm not sure about the terminology)

从第二个链接开始,这是更新功能

From the second link, this is the update function

def update(frame):
global P, C, S

# Every ring is made more transparent
C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

# Each ring is made larger
S += (size_max - size_min) / n

# Reset ring specific ring (relative to frame number)
i = frame % 50
P[i] = np.random.uniform(0,1,2)
S[i] = size_min
C[i,3] = 1

# Update scatter object
scat.set_edgecolors(C)
scat.set_sizes(S)
scat.set_offsets(P)

# Return the modified object
return scat,

如何针对茎图调整这种更新功能? stem文档非常简短(实际上,这是我正在学习matplotlib时经常遇到的问题),但是示例代码显示stem的输出是元组markerline, stemlines, baseline,而不是像plt.plotplt.imshow这样的艺术家对象.

How can I adapt this kind of update function for a stem plot? The documentation for stem is horribly brief (in fact this is a recurring issue as I'm learning matplotlib), but the example code shows that the output of stem is a tuple markerline, stemlines, baseline rather than an artist object like for plt.plot or plt.imshow.

因此,当我为动画编写update函数时,如何更新主干图中的数据?

So when I write my update function for the animation, how can I update the data inside the stem plot?

推荐答案

去这里!

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

import numpy as np

fig, ax = plt.subplots()
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = ax.stem(x, np.cos(x), '-.')

def update(i):
    ax.cla()
    markerline, stemlines, baseline = ax.stem(x, np.cos(x+i/10), '-.')
    ax.set_ylim((-1, 1))

anim = FuncAnimation(fig, update, frames=range(10, 110, 10), interval=500)
anim.save('so.gif', dpi=80, writer='imagemagick')

我认为可以有更好的方法来实现此目的-无需每次都清除情节.但是,这可行!

I think there can be better ways of achieving this- not requiring to clear the plot each time. However, this works!

这篇关于在matplotlib中对茎图进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆