首页 > 解决方案 > 如何将_xticklabels 设置为pandas DataFrame 的相应“日期”列?

问题描述

问题

我有一个熊猫数据框,其中包含两列数据和另一列中的相应日期时间。我想为这两组数据制作一个线图,并将日期时间(字符串列表)作为 x 轴刻度标签。但是当我制作绘图时,刻度标签与该日期的相应数据不一致。相反,xlabels 只是来自日期列的前 n 个条目。

我的原始程序在每个数据点都有一个刻度,所以我尝试设置 ax.set_xticks 以减少刻度数,这就是这个问题出现的时候。

编码

import numpy             as     np
import datetime
import pandas            as     pd
import matplotlib.pyplot as     plt
% matplotlib inline

data = { 'Set1': np.random.rand(24),
         'Set2': np.random.rand(24)
       }
df = pd.DataFrame(data,columns=['Set1','Set2'])

date_list = []
base = datetime.datetime(2000,1,1,0)
for i in range(len(df.Set1)):
    date = base + datetime.timedelta(hours=i*3)
    date_frmt = date.strftime("%b%d%Hz")
    date_list.append(str(date_frmt))
df['Dates'] = date_list

print(df)
    Set1      Set2      Dates
0   0.521824  0.371057  Jan0100z
1   0.726503  0.945712  Jan0103z
2   0.881100  0.725798  Jan0106z
3   0.432198  0.549191  Jan0109z
4   0.083255  0.297057  Jan0112z
5   0.428145  0.441973  Jan0115z
6   0.168049  0.411889  Jan0118z
7   0.654588  0.822227  Jan0121z
8   0.540984  0.824515  Jan0200z
9   0.999410  0.809121  Jan0203z
10  0.055359  0.901241  Jan0206z
11  0.163407  0.085901  Jan0209z
12  0.523488  0.011856  Jan0212z
13  0.133038  0.881413  Jan0215z
14  0.880946  0.301656  Jan0218z
15  0.575265  0.972408  Jan0221z
16  0.489332  0.399983  Jan0300z
17  0.119246  0.216152  Jan0303z
18  0.805346  0.873699  Jan0306z
19  0.806190  0.277772  Jan0309z
20  0.868357  0.311854  Jan0312z
21  0.042386  0.461695  Jan0315z
22  0.354832  0.262534  Jan0318z
23  0.209049  0.780153  Jan0321z
 ax = df.plot(figsize=(10, 5))
 ax.set_xticklabels(df.Dates)

在此处输入图像描述

问题

如何让刻度的标签与其相应的数据正确对齐?

标签: pythonpandasdatetimematplotlibaxis-labels

解决方案


您可以使用 pyplot 的DateFormatter

fig, ax = plt.subplots()
for col in ['Set1', 'Set2']:
    ax.plot(df['Dates'], df[col], label=col)

ax.legend()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b%d%Hz'))

输出:

在此处输入图像描述


推荐阅读