2

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?

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
gaurav gurnani
  • 2,789
  • 3
  • 19
  • 18
  • possible duplicate of [Plotting dates on the x-axis with Python's matplotlib](http://stackoverflow.com/questions/9627686/plotting-dates-on-the-x-axis-with-pythons-matplotlib) – Jonathan Davies Feb 18 '15 at 22:49

1 Answers1

2

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

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Hey, thanks for the reply. But this is not what i want... i want my line to be plotted using numbers... i have to pass this line to a mpld3 plugin and it should be JSON serializable. I want to plot the line using my array x but display dates on the x ticks instead.. can you think of something ? – gaurav gurnani Feb 19 '15 at 07:57
  • My apologies.. this code worked.. I wasn't thinking straight. thank you – gaurav gurnani Feb 19 '15 at 13:35