Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dates along x-axis of quadmesh

I would like to use matplotlib and Axes.pcolormesh to create a plot. My problem is that I want to have dates along the x-axis:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
qmesh = ax.pcolormesh(times,mlt,data.T)
fig.colorbar(qmesh,ax=ax)

in this code, times is a (1D) numpy array created using matplotlib.dates.date2num. This creates a perfectly reasonable plot except that the x-axis is labeled with values on the order of 1e5 instead of dates/times in the format '%H:%M'. Any suggestions would be appreciated. Thanks.

like image 359
mgilson Avatar asked Mar 24 '23 17:03

mgilson


2 Answers

In addition to the answer you already found, you can do ax.xaxis_date(), which is effectively equivalent.

As a quick example (which also uses fig.autofmt_xdate() to rotate the x-labels):

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt

# Generate some data
x = mdates.drange(dt.datetime(2012, 01, 01), dt.datetime(2013, 01, 01),
                  dt.timedelta(weeks=2))
y = np.linspace(1, 10, 20)
data = np.random.random((y.size, x.size))

# Plot
fig = plt.figure()
ax = fig.add_subplot(111)
qmesh = ax.pcolormesh(x, y, data)
fig.colorbar(qmesh,ax=ax)
ax.axis('tight')

# Set up as dates
ax.xaxis_date()
fig.autofmt_xdate()

plt.show()

enter image description here

like image 152
Joe Kington Avatar answered Apr 02 '23 00:04

Joe Kington


Turns out I needed a:

import matplotlib.dates as dates
ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

in there.

like image 30
mgilson Avatar answered Apr 01 '23 23:04

mgilson