首页 > 解决方案 > Python 显示时间跨度

问题描述

我创建了一个图表,您可以在其中查看可视化数据和数据趋势。是否可以按时间跨度切割图表?

这是我的图表代码

import matplotlib.pyplot as plt
import matplotlib.dates as mdates


fig, ax = plt.subplots()
ax.grid(True)
year = mdates.YearLocator(month=1)
month = mdates.MonthLocator(interval=3)
year_format = mdates.DateFormatter('%Y')
month_format = mdates.DateFormatter('%m')
ax.xaxis.set_minor_locator(month)
ax.xaxis.grid(True, which = 'minor')
ax.xaxis.set_major_locator(year)
ax.xaxis.set_major_formatter(year_format)
plt.plot(df.index, df['JAN'], c='blue')
plt.plot(decomposition.trend.index, decomposition.trend, c='red')

在此处输入图像描述

我有这段代码来缩短图表,但我不知道如何在上面的代码中使用它。


start_date = datetime(2004,1,1)
end_date = datetime(2008,1,1)
df[(start_date<=df.index) & (df.index<=end_date)].plot(grid='on')

在此处输入图像描述

标签: pythonpandasmatplotlibcharts

解决方案


您可以使用plt.xlim来调整日期范围,

plt.xlim([datetime(2004, 1, 1), datetime(2008, 1, 1)])

这会给你一个看起来像的x轴

在此处输入图像描述


推荐阅读