Displaying an inverted vertical date axis

一笑奈何 提交于 2019-12-11 11:59:29

问题


The chart I'm trying to make is a 2D-array with date as its vertical dimension. By convention, the dates should increase from the top down. Displaying the date the other way around works fine with this code:

import numpy as np
import matplotlib as mpl
import matplotlib.colorbar as cb
import matplotlib.pyplot as plt
from datetime import datetime

y = np.reshape(np.random.rand(100), (10, 10))
f1 = plt.figure()
ax1 = f1.add_axes([0.15, 0.15, 0.76, 0.80])
mindate = mpl.dates.date2num(datetime(2010, 1, 10))
maxdate = mpl.dates.date2num(datetime(2010, 1, 20))
im1 = ax1.imshow(y, cmap='binary', aspect='auto', origin='upper',
                 interpolation='nearest', extent=(0, 1, mindate, maxdate))
ax1.yaxis_date()
plt.show()

Reversing the direction of an axis is quite simple with other data types by switching interval boundaries, but with date this results in an empty Y axis. Is there a way to get this working without writing a custom tick locator?


回答1:


It's too bad that inverting a datetime axis obliterates the ticklocator and formatting settings. The easiest thing I can figure is to manually re-set them. Here's a link to the format table. Here's a link to DateFormatter. You could also probably use AutoDateFormatter.

Here's the code:

import numpy as np
import matplotlib as mpl
import matplotlib.colorbar as cb
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib import dates

y = np.reshape(np.random.rand(100), (10, 10))
f1 = plt.figure()
ax1 = f1.add_axes([0.15, 0.15, 0.76, 0.80])
mindate = mpl.dates.date2num(datetime(2010, 1, 10))
maxdate = mpl.dates.date2num(datetime(2010, 1, 20))
im1 = ax1.imshow(
    y, cmap='binary', aspect='auto',
    origin='upper', interpolation='nearest',
    extent=(0, 1, mindate, maxdate))

ax1.yaxis_date()

ax1.invert_yaxis()
hfmt = dates.DateFormatter('%b %d %Y')
ax1.yaxis.set_major_locator(dates.DayLocator(interval=1))
ax1.yaxis.set_major_formatter(hfmt)

plt.show()

It produces this:



来源:https://stackoverflow.com/questions/5804969/displaying-an-inverted-vertical-date-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!