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))
>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))