在 Python 中反转日期时间的 y 轴

Inverting y axis of datetimes in Python

我正在尝试生成一个图表,其中 y 轴上有日期时间对象,从上到下递增。 This answer 建议使用 invert_yaxis(),它会抛出 'ValueError: No sensible date limit could be found in the AutoDateLocator.' 手动设置 ymin 和 ymax 会得到相同的结果。我错过了什么?

提前致谢!

编辑:我在 Python 2.7.

上使用 matplotlib 1.3.1
import numpy
import matplotlib.pyplot as plt
import datetime

#set up x and y
dates = dates = [datetime.datetime(2015, 3, 12), datetime.datetime(2015, 3, 15), datetime.datetime(2015, 3, 17), datetime.datetime(2015, 3, 21), datetime.datetime(2015, 3, 9), datetime.datetime(2015, 3, 16)]
x = numpy.arange(0, len(dates), 1)

plt.figure()
plt.plot(x, dates)
plt.gca().invert_yaxis() #this is the bit that isn't working!
plt.show()

您始终可以手动设置所有内容:

import numpy
import matplotlib.pyplot as plt
import datetime

#set up x and y
dates = [datetime.datetime(2015, 3, 12), datetime.datetime(2015, 3, 15), datetime.datetime(2015, 3, 17), datetime.datetime(2015, 3, 21), datetime.datetime(2015, 3, 9), datetime.datetime(2015, 3, 16)]
x = numpy.arange(0, len(dates), 1)
## create a time axis in seconds
tim = [(date-dates[0]).total_seconds() for date in dates]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, tim)
# get the y-axis limits
ylim = ax.get_ylim()
# invert the y-axis
ax.set_ylim(ylim[::-1])

# create ticks and tick labels
nticks = 5
timarr = numpy.linspace(ylim[-1], ylim[0], nticks)
labels = [(dates[0]+datetime.timedelta(seconds=t)).strftime('%m/%d/%Y') for t in timarr]
ax.set_yticks(timarr)
ax.set_yticklabels(labels)

plt.show()