Python使用Matplotlib画以日期为X轴的图

发布时间 2023-04-03 21:07:06作者: 酱_油

Python使用Matplotlib画以日期为X轴的图

步骤:

  1. 用pd把字符串格式的日期转成date格式.
  2. 使用 AutoDateLocator 设置x轴的属性.
 1 from matplotlib import pyplot  as plt
 2 import pandas as pd
 3 from matplotlib.dates import (
 4     MonthLocator,
 5     AutoDateLocator,
 6     AutoDateFormatter,
 7 )
 8 
 9 fcst = [
10             ['20220301',100],
11             ['20220302',110],
12             ['20220303',120],
13             ['20220304',130],
14             ['20220305',140],
15             ['20220306',150],
16             ['20220307',140],
17             ['20220308',130],
18             ['20220408',105],
19 ]
20 
21 fcst = pd.DataFrame(fcst,columns=['ds','yhat'])
22 fcst['ds'] = pd.to_datetime(fcst['ds'])
23 fcst_t = fcst['ds'].dt.to_pydatetime()
24 
25 
26 fig = plt.figure(facecolor='w', figsize=(10,6))
27 ax = fig.add_subplot(111)
28 
29 ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2')
30 
31 locator = AutoDateLocator(interval_multiples=False)
32 formatter = AutoDateFormatter(locator)
33 ax.xaxis.set_major_locator(locator)
34 ax.xaxis.set_major_formatter(formatter)
35 
36 plt.show()

 

示意图: