所以,首先要列出要用直方图表示的日期列表: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]import numpy
histo = numpy.histogram(num_dates)
因为您需要累积直方图,所以可以将各个计数相加:cumulative_histo_counts = histo[0].cumsum()
柱状图需要箱子大小: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()调用中调整显示日期的方式。