Nickj
Nickj

Reputation: 1012

get the date format on a Matplotlib plot's x-axis

I generate a plot using the following code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

index=pd.date_range('2018-01-01',periods=200)
data=pd.Series(np.random.randn(200),index=index)

plt.figure()
plt.plot(data)

Which gives me a plot, looking as follows:

Random timeseries

It looks like Matplotlib has decided to format the x-ticks as %Y-%m (source)

I am looking for a way to retrieve this date format. A function like ax.get_xtickformat(), which would then return %Y-%m. Which is the smartest way to do this?

Upvotes: 1

Views: 1230

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

There is no built-in way to obtain the date format used to label the axes. The reason is that this format is determined at drawtime and may even change as you zoom in or out of the plot.

However you may still determine the format yourself. This requires to draw the figure first, such that the ticklocations are fixed. Then you may query the formats used in the automatic formatting and select the one which would be chosen for the current view.

Note that the following assumes that an AutoDateFormatter or a formatter subclassing this is in use (which should be the case by default).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

index=pd.date_range('2018-01-01',periods=200)
data=pd.Series(np.random.randn(200),index=index)

plt.figure()
plt.plot(data)

def get_fmt(axis):
    axis.axes.figure.canvas.draw()
    formatter = axis.get_major_formatter()
    locator_unit_scale = float(formatter._locator._get_unit())       
    fmt = next((fmt for scale, fmt in sorted(formatter.scaled.items())
                if scale >= locator_unit_scale),
                       formatter.defaultfmt)
    return fmt

print(get_fmt(plt.gca().xaxis))
plt.show()

This prints %Y-%m.

Upvotes: 2

Joe
Joe

Reputation: 12417

If you want to edit the format of the date in myFmt = DateFormatter("%d-%m-%Y"):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

index=pd.date_range('2018-01-01',periods=200)
data=pd.Series(np.random.randn(200),index=index)
fig, ax = plt.subplots()
ax.plot(index, data)

myFmt = DateFormatter("%d-%m-%Y")
ax.xaxis.set_major_formatter(myFmt)
fig.autofmt_xdate()

plt.show()

Upvotes: 1

Related Questions