Changing the formatting of a datetime axis in matplotlib

Sheryl picture Sheryl · May 14, 2017 · Viewed 47.8k times · Source

I have a series whose index is datetime that I wish to plot. I want to plot the values of the series on the y axis and the index of the series on the x axis. The Series looks as follows:

2014-01-01     7
2014-02-01     8
2014-03-01     9
2014-04-01     8
...

I generate a graph using plt.plot(series.index, series.values). But the graph looks like:

graph

The problem is that I would like to have only year and month. However, the graph contains hours, minutes and seconds. How can I remove them so that I get my desired formatting?

Answer

andrew_reece picture andrew_reece · May 15, 2017
# sample data
import numpy as np
import pandas as pd

N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

# use formatters to specify major and minor ticks
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_=plt.xticks(rotation=90)    

time series plot