Home > Mobile >  How to show years in x-axis using matplotlib?
How to show years in x-axis using matplotlib?

Time:10-26

I have date-wise data to plot but not all consecutive dates available. However, on x-axis I have to show years only. I have tried set_major_locator, YearLocator, MonthLocator etc but it didnt work. Also, I made sure to have dates in datetime format.

After trying these, still some years are missing in graph as marked in below screen shot.

Output: Graph screenshot

Code:

plt.figure(figsize=(15,5))
ax1 = plt.subplot(111)
ax1.set_xticks(np.arange(len(dates)))
ax1.set_xticklabels(dates)
ax1.tick_params(axis='x',rotation=90, zorder=120)
ax1.xaxis.set_major_locator(YearLocator(1,month=1,day=1)) 
plt.plot(dates,baseData.Sabic, linewidth=3)
plt.plot(dates,baseData.PriceDivReinv, linewidth=3)
plt.plot(dates,baseData.PricePlusAccDividend, linewidth=3)
ax1.margins(x=0)
plt.show()

Also, i am unable to get year only using datetime.DateFormatter('%Y')

So, i need help with showing all available years in x-axis.

CodePudding user response:

IIUC, you want to reformate your ax1.set_xticklabels() to yearly strings?

Well since I dont know what your data looks like I am just gonna do with a list comprehension with a bunch of strings

import datetime as dt
dates = ['22-7-1997','1-12-1996','17-06-1992','10-09-1999']
dates = [dt.datetime.strptime(date_string, "%d-%m-%Y").year for date_string in dates]
# Will give you only years

After that just pass your list as an argument in ax1.set_xticklabels(dates)

CodePudding user response:

xtics are supposed to contain location on the x axis. And on the xaxis you have dates. So, xtics are supposed to be dates. But you filled it with numbers (from arange) that will match nothing.

I am even surprised that you get what you described, since you should have got not labels at all.

So, you are not using ax1.set_xticks and ax1.set_xtickslabels right. And, anyway, I don't think you need them here. Just remove those two lines, and, as far as I can tell without a reproducible example, you should be ok.

My own minimal reproducible example of what I understand of your problem and its solution

import matplotlib.pyplot as plt
import numpy as np
import datetime
from matplotlib.dates import YearLocator

plt.figure(figsize=(15,5))
ax1 = plt.subplot(111)
dates=[datetime.datetime(2005,1,1) i*datetime.timedelta(days=10) for i in range(300)]
ax1.tick_params(axis='x',rotation=90, zorder=120)
ax1.xaxis.set_major_locator(YearLocator(1,month=1,day=1))
plt.plot(dates,np.sin(0.1*np.arange(300)), linewidth=3)
ax1.margins(x=0)
plt.show()

It plots a curve of whatever, with dates on the x-axis, and years as labels.

  • Related