gpt4 book ai didi

python - 使用日期时间对象

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:40 28 4
gpt4 key购买 nike

下面的第 1 部分说明了如何使用日期时间对象绘制曲线。

Part 2说明如何使用 float 绘制一组线段。

第 3 部分 仅混合了第 1 部分和第 2 部分,但它失败了。为什么?

import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import collections as mc

#----------------Part 1----------------
d0 = datetime.datetime(2001, 1, 1)
d1 = datetime.datetime(2002, 1, 1)
d2 = datetime.datetime(2003, 1, 1)
d3 = datetime.datetime(2005, 1, 1)
d4 = datetime.datetime(2007, 1, 1)
d5 = datetime.datetime(2009, 1, 1)

date = [ d0, d1, d2, d3, d4, d5 ]
price = [ 5, 4, 6, 7, 3, 8 ]

plt.plot(date, price)
plt.show()

#----------------Part 2----------------
lines = [ [ (0.5, 1.2), (1.1, 1.3) ],
[ (2.2, 2.8), (3.1, 4.2) ],
[ (1.9, 2.9), (0.2, 1.4) ] ]

lc = mc.LineCollection(lines)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
plt.show()

#----------------Part 3----------------
lines = [ [ (d0, 1.2), (d1, 1.3) ],
[ (d2, 2.8), (d3, 4.2) ],
[ (d4, 2.9), (d5, 1.4) ] ]

lc = mc.LineCollection(lines)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)

plt.show()

更新

线

lc = mc.LineCollection(lines)

在第 3 部分中出现错误:

Traceback (most recent call last):
File "datetime-difficulty.py", line 37, in <module>
lc = mc.LineCollection(lines)
File "/lib/python/matplotlib/collections.py", line 897, in __init__
self.set_segments(segments)
File "/lib/python/matplotlib/collections.py", line 906, in set_segments
seg = np.asarray(seg, np.float_)
File "/lib/python/numpy/core/numeric.py", line 235, in asarray
return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number

最佳答案

看起来您正在使用 matplotlib,因此您需要将日期转换为 float 才能让绘图生效。值得庆幸的是,matplotlib 提供了 date2num()功能。通过该函数运行所有日期,matplotlib 应该能够为您提供有意义的 x 轴(取决于格式化程序/定位器)。

关于python - 使用日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28120545/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com