IcemanBerlin
IcemanBerlin

Reputation: 3437

How to format Dates on x axis for matplotlib

I am trying to get a dataframe column to display the date as example "Jan 15, Feb 15 etc" on a chart. But it was displaying as "Feb 115, Mar 115 etc" I have tried to adapt some code using matplotlib.ticker. but then the chart comes out with no axis. Here is a simplified version of the code, not working.

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


# create figure instance
fig1 = plt.figure(1)

ax = fig1.add_subplot(2,1,1)

x = 41640, 41671, 41699, 41730, 41760, 41791

y = 1, 4, 7, 9, 15, 18

ax.get_xaxis().set_major_formatter(
    tkr.FuncFormatter(lambda x, p: format((x), '%b %y')))


ax.plot_date(x, y)
fig1.show()

Upvotes: 2

Views: 2812

Answers (1)

azalea
azalea

Reputation: 12640

Here is some working code:

import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
import matplotlib.dates as mdates
import datetime

# create figure instance
fig1 = plt.figure(1)
ax = fig1.add_subplot(2,1,1)

start_date = datetime.date(1899, 12, 30)
x = 41640, 41671, 41699, 41730, 41760, 41791
dates = [start_date + datetime.timedelta(xval) for xval in x]
y = 1, 4, 7, 9, 15, 18

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator(bymonthday=(1,15)))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
plt.plot(dates, y, 'o')
plt.show()

Explanation:

It turns out serial dates in MS Excel start from Dec 30, 1899. i.e. number 0 is Dec 30, 1899, and 1 corresponds to Dec 31, 1899 (try it out in Excel yourself ^_^). Although the Excel help says that "January 1, 1900 is serial number 1", it is incorrect, since there was an early bug that seems to be fixed.

To convert the Excel serial dates to a Python datetime object, checkout datetime.timedelta.

To plot datetime in matplotlib, checkout its demo and API.

Upvotes: 3

Related Questions