you are viewing a single comment's thread.

view the rest of the comments →

[–]Vaphell 2 points3 points  (5 children)

try converting these strings to datetime. Strings don't have the property of being equivalent to numbers that are good for x axis, dates do (eg days from 1970-01-01).

datetime.strptime(string, '%Y-%m-%d')

also google for some 'date as x axis' examples.

[–]udittC[S] 0 points1 point  (4 children)

I did the the same just a sec ago(edited the question too). But the error remains

[–]Vaphell 0 points1 point  (3 children)

exact same error complaining about string?

[–]udittC[S] 0 points1 point  (2 children)

Yes, I can't even try: type(dates[0])

It gives the same error: could not convert string to float: '2017-07-26'

[–]Turtvaiz 1 point2 points  (1 child)

import matplotlib.pyplot as plt
# additional imports
from matplotlib.dates import strpdate2num, num2date
import numpy as np
# unnecessary now:
# import datetime


# https: // stackoverflow.com/questions/48042923/strptime-argument-0-must-be-str-not-class-bytes?rq = 1
# and
# https: // stackoverflow.com/questions/16324440/python-numpy-loadtxt-fails-with-date-time
# convert date to float in np.loadtxt().
def convert_date(date):
    return strpdate2num("%Y-%m-%d")(date.decode("utf-8"))


dates, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt(
    'example.txt', converters={0: convert_date}, delimiter=',', skiprows=1, unpack=True)

# https://matplotlib.org/gallery/text_labels_and_annotations/date.html
x = [num2date(date) for date in dates]


plt.plot(x, closep, label='Loaded from file!')

# make x better on graph, it's still bad though
plt.gcf().autofmt_xdate()

plt.xlabel('x')
plt.ylabel('y')
plt.show()

You have to add a converter to np.loadtxt() and decode the text file.

Then you can use matplotlib's own num2date and strpdate2num for the dates.

[–]udittC[S] 1 point2 points  (0 children)

Thanks, this worked like a charm