【问题标题】:Dynamically showing the last data value on an animated plot动态显示动画图上的最后一个数据值
【发布时间】:2021-10-15 19:19:47
【问题描述】:

在这个动画情节的顶部,related to a previous project,为了使其更形象化,我希望值显示在点的顶部,但仅适用于最后一个数据,随着动画的进行。

下面的代码显示了所有的注释,因为动画添加了数据,所以最后一团糟……谁能帮我解决这个问题?

我尝试在注释的执行下方添加plt.pause()remove(),但结果发现注释总是在数据点之前......我不知道为什么......

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


def collatz(k):
    seq = [k]
    while seq[-1] > 1:
       if k % 2 == 0:
         seq.append(k/2)
       else:
         seq.append(3*k+1)
       k = seq[-1]
    return seq

y= collatz(22)
x = list(range(len(y)))
  
fig = plt.figure()
plt.xlim(1,len(y))
plt.ylim(1,max(y))

draw, = plt.plot([],[], marker='o', markersize='4', color='magenta') 

def update(idx):
    draw.set_data(x[:idx], y[:idx])
    plt.gca()
    ann = plt.annotate(f'{y[idx]:.1f}', (x[idx],y[idx]), textcoords="offset points", xytext=(0,0.5), ha="center")
    #plt.pause(0.5)
    #ann.remove()
    return draw,

a = FuncAnimation(fig, update, frames=len(x), interval=30, repeat=False)

plt.show()

【问题讨论】:

  • 您的意思是在每个循环中删除除最后一个点之外的所有点,还是我误解了?
  • @flyinthelotion 您好,感谢您的快速回复。由于它是在图形上动态显示数据的动画,所以我想要的是,每次图形更新时显示最后一个值。所以这将与 Veritasium 的视频 link 完全一样,他不仅动态绘制图形,还同时显示最后的值
  • 我添加了我的更新答案,我第一次误解了

标签: python matplotlib animation plot data-visualization


【解决方案1】:

您应该将文本放置为matplotlib.text,而不是注释并将其与draw 一样返回:

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


def collatz(k):
    seq = [k]
    while seq[-1] > 1:
        if k%2 == 0:
            seq.append(k/2)
        else:
            seq.append(3*k + 1)
        k = seq[-1]
    return seq


y = collatz(22)
x = list(range(len(y)))

fig = plt.figure()
plt.xlim(1, len(y))
plt.ylim(1, max(y))

draw, = plt.plot([], [], marker = 'o', markersize = '4', color = 'magenta')
ax = plt.gca()
text = ax.text(0.5, 0.5, '')

def update(idx):
    draw.set_data(x[:idx + 1], y[:idx + 1])
    text.set_text(f'{y[idx]:.1f}')
    text.set_position((x[idx], y[idx]))
    return draw, text,

a = FuncAnimation(fig, update, frames = len(x), interval = 30, repeat = False)

plt.show()

【讨论】:

  • 甜蜜!非常感谢!我还是有点疑惑,为什么draw.set_data(x[:idx + 1], y[:idx + 1])这个意思是马上更新下一点?
  • 不,在 python [a, b] 中,切片是包含开头和结尾的。这意味着 a 包括在内, b 不包括在内。因此,如果当前点是idx,则将文本放在idx-th 位置,然后绘制从第一个点到idx + 1-th 点的曲线(这样idx-th 就包括在内,@ 987654332@-th 不是)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多