Ewdlam
Ewdlam

Reputation: 935

Matplotlib display only years instead of each 1st January in x axis containing dates

I have this dataframe :

import pandas as pd
import datetime
from sklearn.utils import check_random_state
import math
start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("17-03-2017", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
X = [d.strftime('%d-%m-%Y') for d in date_generated] # I need this format for my real dataframe
Y = [math.cos(i) for i in range(1000)]
df = pd.DataFrame(dict(date=X,value=Y))

df.head(3)
         date     value
0  21-06-2014  1.000000
1  22-06-2014  0.540302
2  23-06-2014 -0.416147

df.tail(3)
           date     value
997  14-03-2017 -0.440062
998  15-03-2017  0.517847
999  16-03-2017  0.999650

When I plot the two columns of my dataframe through the following way, x-axis is unreadable :

from matplotlib import pyplot as plt
plt.figure(figsize=(20, 5))
plt.plot(df["date"].values,df["value"].values)
plt.show()

enter image description here

How please could I display only the years, one time each, instead of each 1st January ? In that case, I would like therefore to have only 2015, 2016 and 2017 displayed in x-axis

Upvotes: 3

Views: 4501

Answers (1)

Liris
Liris

Reputation: 1511

You can use matplotlib.dates locator and formatter to format directly the datetime objects that you want to put on the xaxis:

import pandas as pd
import datetime
from sklearn.utils import check_random_state
import math
from matplotlib import pyplot as plt
import matplotlib.dates as mdates

start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("17-03-2017", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
Y = [math.cos(i) for i in range(1000)]


formatter = mdates.DateFormatter("%Y") ### formatter of the date
locator = mdates.YearLocator() ### where to put the labels

fig = plt.figure(figsize=(20, 5))
ax = plt.gca()
ax.xaxis.set_major_formatter(formatter) ## calling the formatter for the x-axis
ax.xaxis.set_major_locator(locator) ## calling the locator for the x-axis
plt.plot(date_generated, Y)
# fig.autofmt_xdate() # optional if you want to tilt the date labels - just try it
plt.tight_layout()
plt.show()

enter image description here

Upvotes: 4

Related Questions