3

I have a timeseries of 10+ years and want to abbreviate the xtick labels to 2-digit years. How can I do that ?

import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
import pandas.io.data as web

stocklist = ['MSFT']

# read historical prices for last 11 years
def get_px(stock, start):
    return web.get_data_yahoo(stock, start)['Adj Close']

today = dt.date.today()
start = str(dt.date(today.year-11, today.month, today.day))
px = pd.DataFrame({n: get_px(n, start) for n in stocklist})
plt.plot(px.index, px[stocklist[0]])
plt.show()
ronnydw
  • 923
  • 16
  • 24

2 Answers2

2

This digs into the pandas internals in questionable ways, but

ax = plt.gca()
ax.get_xaxis().get_major_formatter().scaled[365] = '%y'
plt.draw()

format spec

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • name 'ax' is not defined. Do I have to create a subplot to use this? – ronnydw Jan 13 '13 at 22:08
  • 2
    See my rambling here about the state machine vs OO interface for matplotlib http://stackoverflow.com/questions/14254379/how-can-i-attach-a-pyplot-function-to-a-figure-instance/14261698#14261698 The state machine interface is useful for testing, but you really should learn the OO interface for writing programatic things. – tacaswell Jan 13 '13 at 22:13
  • The OO interface is basically infinitely better. – PMende Aug 10 '18 at 17:27
1

I found this code and you can modify the format:

ax = plt.gca()
xax = ax.get_xaxis()  # get the x-axis
adf = xax.get_major_formatter()  # get the auto-formatter

adf.scaled[1. / 24] = '%H:%M'  # set the < 1d scale to H:M
adf.scaled[1.0] = '%Y-%m-%d'  # set the > 1d < 1m scale to Y-m-d
adf.scaled[30.] = '%y-%b'  # set the > 1m < 1Y scale to Y-m
adf.scaled[365.] = '%Y'  # set the > 1y scale to Y

Notice the line that says adf.scaled[30.] = '%y-%b' # set the > 1m < 1Y scale to Y-m. The little y indicates a 2-digit year (big Y is 4-digit), and the little b indicates a 3-char month (little m indicates numeric month). I believe these are pretty standard format types in Python.

Uclydde
  • 1,414
  • 3
  • 16
  • 33
Mattchoo
  • 401
  • 4
  • 7