0

I have been at it a day and a half and I guess it's time to call for some help. The following code gives the error:

TypeError: float() argument must be a string or a number, not 'datetime.datetime'

I try to put the datetime variable generated in function frames1, on the x-axis through the animation function.

Code:

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()

I have tried the following solutions:

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

Changing the formatting of a datetime axis in matplotlib

With no positive outcome so far.

I very much thank you in advance for looking at this problem.

JayDough
  • 91
  • 1
  • 10

1 Answers1

1

Not sure why you append 1 to your array in the first place. I guess you mean

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

Then inside the generator function, there is a lot I don't understand. To me it seems you can leave out most of the back and forth conversion and just use now() as it is.

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))

You may however format the axis to show times instead of numbers. Inside the init function you may add

line.axes.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))

where you have imported matplotlib.dates as mdates.

The line imin = min(max(0, i - win), len(x) - win) does not seem to make much sense, why not use max(0, i - win) alone?

So in total a working version could look like this:

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()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712