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开发者_StackOverflow社区 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?
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:
精彩评论