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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
My apologies.. this code worked.. I wasn't thinking straight. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.