【问题标题】:TypeError: Datetime on x-axis through matplotlib animationTypeError:通过matplotlib动画在x轴上的日期时间
【发布时间】:2018-06-09 10:13:15
【问题描述】:

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

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

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

代码:

import random
import time
from matplotlib import pyplot as plt
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 = []
y = []
x.append(1)
y.append(1)

def init():
    line.set_data(x[:1],y[:1])
    return line,

def animate(args):
    # Args are the incoming value that are animated    
    animate.counter += 1
    i = animate.counter
    win = 60
    imin = min(max(0, i - win), len(x) - 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, #line2
animate.counter = 0

def frames1():
    # Generating time variable
    x = 10
    target_time = datetime.datetime.now().strftime("%d %B %Y %H:%M:%000")
    # Extracting time
    FMT = "%d %B %Y %H:%M:%S"
    target_time = datetime.datetime.strptime(target_time, FMT)
    target_time = target_time.time().isoformat()    
    # Converting to time object
    target_time = datetime.datetime.strptime(target_time,'%H:%M:%S') 
    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()

我尝试了以下解决方案:

Plotting dates on the x-axis with Python's matplotlib

Changing the formatting of a datetime axis in matplotlib

到目前为止还没有积极的结果。

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

【问题讨论】:

    标签: python python-3.x datetime animation matplotlib


    【解决方案1】:

    不知道为什么你首先将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()
    

    【讨论】:

      猜你喜欢
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2016-01-03
      • 2019-12-19
      • 1970-01-01
      • 2020-06-09
      • 2020-03-24
      相关资源
      最近更新 更多