如何使时间列成为图的x轴?

时间:2016-04-25 13:07:21

标签: python pandas matplotlib plot

我正在使用pandas阅读一个excel文件,并尝试阅读其中一张表来绘制一些结果。以下是我的代码;

df = pd.read_excel('Base_Case-Position.xlsx',sheetname = 'Sheet1', header=0, parse_col="A:E")
print df
   Time        WB        NB       WBO       SBO
0  09:00:00  0.242661  0.839820  0.449634  0.484678
1  10:00:00  0.809247  1.545173  1.129107  1.147414
2  11:00:00  1.519679  2.051029  1.766170  1.699770
3  12:00:00  1.748682  2.291056  2.018005  1.879778
4  13:00:00  1.790151  2.384782  2.123876  1.913225
5  14:00:00  1.966337  2.612614  2.344493  2.094139
6  15:00:00  2.295261  3.030992  2.686752  2.503890
7  16:00:00  2.412628  3.232904  2.772683  2.737191
8  17:00:00  2.476746  3.354741  2.781410  2.923059

我想根据时间绘制WB,NB,WBO和SBO列,并希望将时间列添加为xtick。

以下是我现在这样做的方式,但对我来说不行,因为我手动设置标签。我已经为Xticks创建了一个列表。有没有更好的方法呢?

%matplotlib inline
import matplotlib.pyplot as plt
a = np.arange(9)
plt.scatter(a,df.WB,color='r',alpha=1)
plt.plot(a,df.NB, color='g',alpha=1)
plt.plot(a,df.WBO, color='k',alpha=1)
plt.plot(a,df.SBO,color='m',alpha=1)
plt.xlabel('Time (hr)')
plt.ylabel('Energy Consumption (kWh)')
labels = ['9:00', '10:00', '11:00', '12:00','13:00', '14:00', '15:00', '16:00','17:00']
plt.xticks(a,labels,rotation='horizontal')
plt.grid(True)
plt.tick_params(which='major', length=4)
plt.tick_params(which='minor', length=4)
plt.show()

1 个答案:

答案 0 :(得分:1)

嗯,这是最简单的方法:

df.set_index('Time').plot()
plt.xticks(map(str, df['Time']), rotation=50)
plt.show()

enter image description here