使用matplotlib.dates.date2num将DateTimeIndex转换为序列,并在调用get_xlim()时使用转换后的序列。例如:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
# 创建一些数据
dates = pd.date_range('20200101', periods=4)
data = [0, 1, 0, 2]
# 创建DataFrame
df = pd.DataFrame({'Data': data}, index=dates)
# 绘制图表
fig, ax = plt.subplots()
ax.plot(df.index, df['Data'])
# 转换DateTimeIndex为序列
x = mdates.date2num(df.index)
# 获取x轴范围
x_min, x_max = ax.get_xlim()
print(x_min, x_max)
输出将是x轴范围的下限和上限,例如:
737425.0 737428.0