python – 使用datetime对象

下面的第1部分说明了使用datetime对象绘制曲线.

Part 2示出了使用浮动来绘制一组段.

第3部分仅混合了第1部分和第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,所以你需要将你的日期转换成浮点数才能使你的情节有效.值得庆幸的是,matplotlib提供了
date2num()功能.通过该函数运行所有日期,matplotlib应该能够为您提供有意义的x轴(取决于格式化程序/定位器).

点赞