Plotting Time With Matplotlib: Typeerror: An Integer Is Required
Solution 1:
The error happens because you are passing strings to datetime.time()
which requires integers
If we look at row[0]
, the result will be "16,59,55,51"
. So, this string has to be split up using row[0].split(",")
which creates a list of strings. The contents of this list needs to be converted to integers using int()
, and can then be passed to the datetime.time
function.
Your code will become:
x = []
y = []
withopen('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
forrowin plots:
hours,minutes,seconds,milliseconds = [int(s) for s inrow[0].split(",")]
x.append(time(hours,minutes,seconds,milliseconds))
y.append(float(row[1]))
plt.plot(x,y, marker='o', label='brightness')
plt.gca().invert_yaxis()
plt.xlabel('time [UT]')
plt.ylabel('brightness [mag, CR]')
plt.legend()
plt.grid()
plt.show()
Which gives:
Solution 2:
When you scan in the CSV file your row data contains a string in row[0]. For example, the first line of your csv file becomes:
row = ["16,59,55,51", "13.8"]
To fix this, you need to convert those strings to appropriate values.
withopen('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
forrowin plots:
t = [int(x) for x inrow[0].split(',')]
x.append(time(t[0],t[1],t[2],t[3]))
y.append(float(row[1])
Another option is to use the datetime stamp like so:
from datetime import datetime
x = []
y = []
withopen('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
forrowin plots:
x.append(datetime.strptime(row[0], '%H,%M,%S,%f'))
y.append(float(row[1]))
This will use your milliseconds as microseconds, but that doesn't seem like it's a very big deal to me. It does, however, allow you to add dates later if you need to.
Solution 3:
Your row[0] is a string of numbers separated by commas, e.g. "16,59,55,51".
You'll need to split them into subfields, and then convert each of the smaller numeric strings to actual integers, e.g.:
(hours, minutes, seconds, microseconds) = [int(v) for v in row[0].split(',')]
x.append(time(hours, minutes, seconds, microseconds))
Post a Comment for "Plotting Time With Matplotlib: Typeerror: An Integer Is Required"