Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ax.get_xlim() doesnt work with datetimeindex

ax.get_xlim doesnt provide the right result. When running the code below, I get xmin as 1970-01-01 instead of 2003-01-01.

Does anyone know how to fix it?

data = pd.DataFrame({
    'Date': pd.date_range('1980-01-01', '2023-01-01', freq='M'),
    'Value': np.random.rand(516)
})
data=data.set_index('Date')
data.index=pd.to_datetime(data.index)
data=data.resample('M').last()

data=data['2003-01-01':]
fig, ax = plt.subplots()
xmin, xmax = ax.get_xlim()
ax.plot(data)
print(pd.Timestamp(xmin)) 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First, you should pull the xlims after the plot rather than before. Otherwise, it’s just the default starting [0, 1].

Then you need to use matplotlib.dates.num2date()

from matplotlib import dates

data = pd.DataFrame({
    'Date': pd.date_range('1980-01-01', '2023-01-01', freq='M'),
    'Value': np.random.rand(516)
})
data=data.set_index('Date')
data.index=pd.to_datetime(data.index)
data=data.resample('M').last()

data=data['2003-01-01':]
fig, ax = plt.subplots()

ax.plot(data)
xmin, xmax = ax.get_xlim()

print(dates.num2date(xmin)) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading