Python TypeError:通过matplotlib动画在x轴上显示日期时间

Python TypeError:通过matplotlib动画在x轴上显示日期时间,python,python-3.x,datetime,animation,matplotlib,Python,Python 3.x,Datetime,Animation,Matplotlib,我已经做了一天半了,我想是时候求助了。以下代码给出了错误: TypeError:float()参数必须是字符串或数字,而不是 'datetime.datetime' 我试图通过动画函数将函数frames1中生成的datetime变量放在x轴上 代码: 我尝试了以下解决方案: 目前还没有积极的结果 我非常感谢您提前查看此问题。不确定您首先为什么要将1附加到数组中。我想你是说 # Creating data variables x = [] y = [] x.append(datetime.da

我已经做了一天半了,我想是时候求助了。以下代码给出了错误:

TypeError:
float()
参数必须是字符串或数字,而不是
'datetime.datetime'

我试图通过动画函数将函数frames1中生成的
datetime
变量放在x轴上

代码:

我尝试了以下解决方案:

目前还没有积极的结果


我非常感谢您提前查看此问题。

不确定您首先为什么要将
1
附加到数组中。我想你是说

# Creating data variables
x = []
y = []
x.append(datetime.datetime.now())
y.append(1)
那么在生成器函数中,有很多我不明白的地方。在我看来,您似乎可以省去大部分来回转换,直接使用
now()

def frames1():
    # Generating time variable
    target_time = datetime.datetime.now()

    while True:
        # Add new time + 60 seconds
        target_time = target_time + datetime.timedelta(seconds=60)
        x = target_time
        y = random.randint(250,450)/10
        yield (x,y)  
        time.sleep(random.randint(2,5))
但是,您可以将轴的格式设置为显示时间而不是数字。在
init
函数中,您可以添加

line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
matplotlib.dates
作为
mdates
导入的位置

imin=min(max(0,i-win),len(x-win)
似乎没有多大意义,为什么不单独使用
max(0,i-win)

因此,总的来说,工作版本可能如下所示:

import random
import time
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from matplotlib import animation
import datetime

# Plot parameters
fig, ax = plt.subplots()
line, = ax.plot([], [], 'k-', label = 'ABNA: Price', color = 'blue')
legend = ax.legend(loc='upper right',frameon=False)
plt.setp(legend.get_texts(), color='grey')
ax.margins(0.05)
ax.grid(True, which='both', color = 'grey')

# Creating data variables
x = [datetime.datetime.now()]
y = [1]

def init():
    line.set_data(x[:1],y[:1])
    line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
    return line,

def animate(args):
    # Args are the incoming value that are animated    
    animate.counter += 1
    i = animate.counter
    win = 60
    imin = max(0, i - win)
    x.append(args[0])
    y.append(args[1])

    xdata = x[imin:i]
    ydata = y[imin:i]

    line.set_data(xdata, ydata)
    line.set_color("red")

    plt.title('ABNA CALCULATIONS', color = 'grey')
    plt.ylabel("Price", color ='grey')
    plt.xlabel("Time", color = 'grey')

    ax.set_facecolor('black')
    ax.xaxis.label.set_color('grey')
    ax.tick_params(axis='x', colors='grey')
    ax.yaxis.label.set_color('grey')
    ax.tick_params(axis='y', colors='grey')

    ax.relim()
    ax.autoscale()

    return line,

animate.counter = 0

def frames1():
    # Generating time variable
    target_time = datetime.datetime.now()
    while True:
        # Add new time + 60 seconds
        target_time = target_time + datetime.timedelta(seconds=60)
        x = target_time
        y = random.randint(250,450)/10
        yield (x,y)  
        time.sleep(random.randint(2,5))

anim = animation.FuncAnimation(fig, animate,init_func=init,frames=frames1)

plt.show()

import random
import time
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from matplotlib import animation
import datetime

# Plot parameters
fig, ax = plt.subplots()
line, = ax.plot([], [], 'k-', label = 'ABNA: Price', color = 'blue')
legend = ax.legend(loc='upper right',frameon=False)
plt.setp(legend.get_texts(), color='grey')
ax.margins(0.05)
ax.grid(True, which='both', color = 'grey')

# Creating data variables
x = [datetime.datetime.now()]
y = [1]

def init():
    line.set_data(x[:1],y[:1])
    line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
    return line,

def animate(args):
    # Args are the incoming value that are animated    
    animate.counter += 1
    i = animate.counter
    win = 60
    imin = max(0, i - win)
    x.append(args[0])
    y.append(args[1])

    xdata = x[imin:i]
    ydata = y[imin:i]

    line.set_data(xdata, ydata)
    line.set_color("red")

    plt.title('ABNA CALCULATIONS', color = 'grey')
    plt.ylabel("Price", color ='grey')
    plt.xlabel("Time", color = 'grey')

    ax.set_facecolor('black')
    ax.xaxis.label.set_color('grey')
    ax.tick_params(axis='x', colors='grey')
    ax.yaxis.label.set_color('grey')
    ax.tick_params(axis='y', colors='grey')

    ax.relim()
    ax.autoscale()

    return line,

animate.counter = 0

def frames1():
    # Generating time variable
    target_time = datetime.datetime.now()
    while True:
        # Add new time + 60 seconds
        target_time = target_time + datetime.timedelta(seconds=60)
        x = target_time
        y = random.randint(250,450)/10
        yield (x,y)  
        time.sleep(random.randint(2,5))

anim = animation.FuncAnimation(fig, animate,init_func=init,frames=frames1)

plt.show()