Skip to content Skip to sidebar Skip to footer

Setting Dates As First Letter On X-axis Using Matplotlib

I have time-series plots (over 1 year) where the months on the x-axis are of the form Jan, Feb, Mar, etc, but I would like to have just the first letter of the month instead (J,F,M

Solution 1:

The following snippet based on the official example here works for me.

This uses a function based index formatter order to only return the first letter of the month as requested.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
datafile = cbook.get_sample_data('aapl.csv', asfileobj=False)
print'loading', datafile
r = mlab.csv2rec(datafile)

r.sort()
r = r[-365:]  # get the last year# next we'll write a custom formatter
N = len(r)
ind = np.arange(N)  # the evenly spaced plot indicesdefformat_date(x, pos=None):
    thisind = np.clip(int(x+0.5), 0, N-1)
    return r.date[thisind].strftime('%b')[0]


fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

Solution 2:

I tried to make the solution suggested by @Appleman1234 work, but since I, myself, wanted to create a solution that I could save in an external configuration script and import in other programs, I found it inconvenient that the formatter had to have variables defined outside of the formatter function itself.

I did not solve this but I just wanted to share my slightly shorter solution here so that you and maybe others can take it or leave it.

It turned out to be a little tricky to get the labels in the first place, since you need to draw the axes, before the tick labels are set. Otherwise you just get empty strings, when you use Text.get_text().

You may want to get rid of the agrument minor=True which was specific to my case.

# ...# Manipulate tick labels
plt.draw()
ax.set_xticklabels(
    [t.get_text()[0] for t in ax.get_xticklabels(minor=True)], minor=True
)

I hope it helps:)

Solution 3:

The original answer uses the index of the dates. This is not necessary. One can instead get the month names from the DateFormatter('%b') and use a FuncFormatter to use only the first letter of the month.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from matplotlib.dates import MonthLocator, DateFormatter 

x = np.arange("2019-01-01", "2019-12-31", dtype=np.datetime64)
y = np.random.rand(len(x))

fig, ax = plt.subplots()
ax.plot(x,y)


month_fmt = DateFormatter('%b')
defm_fmt(x, pos=None):
    return month_fmt(x)[0]

ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(FuncFormatter(m_fmt))
plt.show()

enter image description here

Post a Comment for "Setting Dates As First Letter On X-axis Using Matplotlib"