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

时间:2015-03-26 20:50:46

标签: python datetime matplotlib

我试图在y轴上生成一个带有日期时间对象的图形,从上到下增加。 This answer建议使用invert_yaxis(),它会抛出' ValueError:在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()

1 个答案:

答案 0 :(得分:0)

您可以随时手动设置所有内容:

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()