bwrr
bwrr

Reputation: 621

Converting a list of datetime objects using drange to plot in matplotlib gives an error

I have a list of datetime objects which I want to eventually plot within a set range. However when I define this range using drange, I get an error "ValueError: Number of samples, -23, must be non-negative."

Any suggestions where I am going wrong here? Pretty sure my data has no negative values in it.

I'm using Python 3.6.

Here is my code:

import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

date = [datetime.datetime(2017, 8, 24, 0, 0), datetime.datetime(2017, 8, 23, 0, 0), datetime.datetime(2017, 8, 22, 0, 0), datetime.datetime(2017, 8, 21, 0, 0), datetime.datetime(2017, 8, 18, 0, 0), datetime.datetime(2017, 8, 17, 0, 0), datetime.datetime(2017, 8, 16, 0, 0), datetime.datetime(2017, 8, 15, 0, 0), datetime.datetime(2017, 8, 14, 0, 0), datetime.datetime(2017, 8, 11, 0, 0), datetime.datetime(2017, 8, 10, 0, 0), datetime.datetime(2017, 8, 9, 0, 0), datetime.datetime(2017, 8, 8, 0, 0), datetime.datetime(2017, 8, 7, 0, 0), datetime.datetime(2017, 8, 4, 0, 0), datetime.datetime(2017, 8, 3, 0, 0), datetime.datetime(2017, 8, 2, 0, 0), datetime.datetime(2017, 8, 1, 0, 0)]

start = date[0] #is a datetime.datetime object according to type
end = date[-1]  #is a datetime.datetime object according to type   
delta = datetime.timedelta(days=5)
dates = mdates.drange(start, end, delta)
print(dates)
plt.plot(dates, y_data)


#    raise ValueError("Number of samples, %s, must be non-negative." % num)

# ValueError: Number of samples, -23, must be non-negative.

Upvotes: 1

Views: 863

Answers (1)

Bill Bell
Bill Bell

Reputation: 21663

I see that end is less than start but delta is positive. drange works like range. It expects to begin with start and change it by amount delta until it reaches end. I suspect that you should be using -delta in this statement.

As suggested by ImportanceOfBeingErnest in a comment, you could define y_data using:

y_data = range(len(dates))

Upvotes: 3

Related Questions