因此,您从要绘制直方图的日期列表开始:
from datetime import datetime
list_of_datetime_datetime_objects = [datetime(2010, 6, 14), datetime(1974, 2, 8), datetime(1974, 2, 8)]
Matplotlib 允许您将 datetime.datetime 对象转换为简单的数字,正如 David 所提到的:
from matplotlib.dates import date2num, num2date
num_dates = [date2num(d) for d in list_of_datetime_datetime_objects]
然后您可以计算数据的直方图(查看NumPy histogram docs for more options (number of bins, etc.)):
import numpy
histo = numpy.histogram(num_dates)
由于您需要累积直方图,因此您可以将各个计数相加:
cumulative_histo_counts = histo[0].cumsum()
直方图需要 bin 大小:
from matplotlib import pyplot
然后您可以绘制累积直方图:
bin_size = histo[1][1]-histo[1][0]
pyplot.bar(histo[1][:-1], cumulative_histo_counts, width=bin_size)
或者,您可能需要曲线而不是直方图:
# pyplot.plot(histo[1][1:], cumulative_histo_counts)
如果您想要 x 轴上的日期而不是数字,您可以将数字转换回日期并要求 matplotlib 使用日期字符串作为刻度,而不是数字:
from matplotlib import ticker
# The format for the x axis is set to the chosen string, as defined from a numerical date:
pyplot.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: num2date(numdate).strftime('%Y-%d-%m')))
# The formatting proper is done:
pyplot.gcf().autofmt_xdate()
# To show the result:
pyplot.show() # or draw(), if you don't want to block
这里,gca() 和 gcf() 分别返回当前坐标轴和图形。
当然,您可以在上面对strftime() 的调用中调整显示日期的方式。
为了超越您的问题,我想提一下 Matplotlib's gallery 是一个非常好的信息来源:您通常可以通过查找看起来像您正在尝试做的图像来快速找到您需要的内容,并且查看他们的源代码。