使用matplotlib绘制时间:TypeError:需要一个整数 [英] Plotting time with matplotlib: TypeError: an integer is required
问题描述
早上好!
有人可以帮我解决以下问题吗?预先谢谢你!
我有一个带有时间戳(小时、分钟、秒、毫秒)和物体亮度(浮动)的 CSV 文件,如下所示:
16、59、55、51 13.817,00,17,27 13.717,00,39,01 13.617,01,01,06 13.4
这是我的python脚本:
将matplotlib.pyplot导入为plt导入csv从日期时间导入时间x = []y = []使用 open('calibrated.csv','r') 作为 csvfile:地块= csv.reader(csvfile,delimiter ='')对于图中的行:x.append(time(row [0]))y.append(float(row[1]))plt.plot(x,y, marker='o', label='brightness')plt.gca().invert_yaxis()plt.xlabel('时间[UT]')plt.ylabel('亮度[mag,CR]')plt.legend()plt.grid()plt.show()
运行脚本时,出现此TypeError:
回溯(最近一次调用最后一次):在第11行的文件"lightcurve.py"中x.append(时间(行[0]))TypeError:必须为整数
我做错了什么?
发生错误是因为您将 strings 传递给
G'morning all!
Could somebody help me with the following problem? Thank you in advance!
I have a CSV file with time-stamps (hours,minutes,seconds,milliseconds) and brightness of an object in magnitudes (float), like this:
16,59,55,51 13.8 17,00,17,27 13.7 17,00,39,01 13.6 17,01,01,06 13.4
And here is my python script:
import matplotlib.pyplot as plt
import csv
from datetime import time
x = []
y = []
with open('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
for row in plots:
x.append(time(row[0]))
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()
When I run the script, I get this TypeError:
Traceback (most recent call last): File "lightcurve.py", line 11, in x.append(time(row[0])) TypeError: an integer is required
What am I doing wrong?
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 = []
with open('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
for row in plots:
hours,minutes,seconds,milliseconds = [int(s) for s in row[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:
这篇关于使用matplotlib绘制时间:TypeError:需要一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!