gaurav gurnani
gaurav gurnani

Reputation: 2859

replace numbers on X axis with dates when using line plot in matplotlib

I am plotting a straight line plot with an array of numbers

fig, ax = plt.subplots()
ax.plot(x, 0 * x)

x is the array:

array([  0,1,2,3,4,5,6,7,8,9,10 ])

The line is fine but I want to display dates on the x axis.. I want to associate a date with each of the number and use those as my x ticks.

Can anyone suggest something?

Upvotes: 2

Views: 2814

Answers (1)

unutbu
unutbu

Reputation: 879919

You can control the ticker format of any value using a ticker.FuncFormatter:

import matplotlib.ticker as ticker
def todate(x, pos, today=DT.date.today()):
    return today+DT.timedelta(days=x)
fmt = ticker.FuncFormatter(todate)
ax.xaxis.set_major_formatter(fmt)

and if the dates appear too crowded, you can rotate them:

fig.autofmt_xdate(rotation=45)  

For example,

import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

x = np.array([0,1,2,3,4,5,6,7,8,9,10])

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, x**2*np.exp(-x))
def todate(x, pos, today=DT.date.today()):
    return today+DT.timedelta(days=x)
fmt = ticker.FuncFormatter(todate)
ax.xaxis.set_major_formatter(fmt)
fig.autofmt_xdate(rotation=45)  
plt.show()

yields

enter image description here

Upvotes: 2

Related Questions