【问题标题】:error with animation of a string - matplotlib字符串动画错误 - matplotlib
【发布时间】:2019-01-21 05:58:37
【问题描述】:

我正在尝试让animationmatplotlib 工作。我以前有这个code 工作,但现在我返回一个错误。我不确定更新是否导致了这种情况?

code 在下方。这是以前的工作。但现在它返回一个错误:

    raise TypeError("invalid type comparison")

TypeError: invalid type comparison

例子:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import pandas as pd

d = ({
    'Time' : [1,2,3,4,5,6,7,8,9,10],                                     
     })

df = pd.DataFrame(data = d)


fig, ax = plt.subplots(figsize = (10,6))

#Event Table
Events_table = plt.table(cellText= [[''],[''],[''],[''],['']],
    colWidths = [1],
    rowLabels=['Time','1','2','3','4'],
    colLabels=['Events'],
    bbox = [0.124, 0.75, 0.236, 0.22])

Frame_number = df['Time']

label = plt.text(-180, 50, Frame_number, fontsize = 8, ha = 'center')

def animate(i) :
    label.set_text(Frame_number[i+1])

ani = animation.FuncAnimation(fig, animate, np.arange(0,10),# init_func = init,
                          interval = 100, blit = False)

plt.draw()

【问题讨论】:

  • 试试label = plt.text(-180, 50, str(Frame_number[0]), fontsize = 8, ha = 'center')label.set_text(str(Frame_number[i+1]))
  • 谢谢@Thomas Kuhn

标签: python pandas matplotlib animation


【解决方案1】:

我怀疑这段代码在以前的版本中是否可行;无论如何都有两个问题:

  • 我想你会想在动画开始之前将你的标签设置为系列的 first 元素。

    label = plt.text(0, 0, Frame_number[0])
    
  • 如果你使用i+1来索引系列,你的动画需要在最后一个索引之前停止一个索引,

    ani = animation.FuncAnimation(..., frames=np.arange(0, len(Frame_number)-1) )
    

完整代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import pandas as pd

df = pd.DataFrame(data = { 'Time' : [1,2,3,4,5,6,7,8,9,10],  })

fig, ax = plt.subplots(figsize = (10,6))

Frame_number = df['Time']

label = plt.text(0, 0, Frame_number[0])

def animate(i) :
    label.set_text(Frame_number[i+1])

ani = animation.FuncAnimation(fig, animate, np.arange(0,len(Frame_number)-1),
                          interval = 100, blit = False)

plt.show()

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 2014-09-28
    • 2018-01-03
    • 2015-09-21
    • 2022-01-21
    • 2021-02-01
    • 2020-10-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多