x轴matplotlib上的良好日期格式

时间:2015-07-29 12:25:46

标签: python matplotlib

我有以下数据框:

Time    test
0:05    2
0:06    2
0:07    2
0:08    2
0:09    2
0:10    2
0:11    2

此数据帧从0:00开始,到11:59结束。我创建了以下图表:

x = dftestgraph['Time']
y = dftestgraph['test']
plt.ylabel('Number of tasks')
plt.plot(x, y, color="#00a1e4", label="Number of Tasks")
plt.fill(x, y, '#00a1e4', alpha=0.8)
plt.show()

Graph

为什么图表底部有一条线,将我填充的图形分成两半?我想将我的x轴格式化为(0:00,0:30,1:00等)我试过:

plt.xticks(0:00, 11:59, 30:00))

然而,这不起作用。 我的问题是:

  • 为什么我的图表中有一行,我该如何解决?
  • 如何以正确的格式设置x轴?

1 个答案:

答案 0 :(得分:7)

plt.fill基本上链接时间序列的第一个和最后一个点来构建其多边形。我会改用fill_between

我在下面放了一个MWE,显示了它是如何完成的。它还显示了一种格式化xaxis标签的方法,它来自以下帖子:Creating graph with date and time in axis labels with matplotlibPlotting time in Python with Matplotlib

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import dates
import datetime

plt.close('all')

#---- generate some data ----

t = [datetime.datetime(2015, 1, 1, 0) + 
     datetime.timedelta(hours=i) for i in np.arange(0,12.1,0.5)]
x = np.random.rand(len(t))

#---- create figure and axe ----

fig = plt.figure()

ax = fig.add_axes([0.1, 0.2, 0.85, 0.75])

#---- format xaxis ----

# position of the labels
xtk_loc = [datetime.datetime(2015, 1, 1, 0) + 
           datetime.timedelta(hours=i) for i in np.arange(0,12.1,0.5)]
ax.set_xticks(xtk_loc)
ax.tick_params(axis='both', direction='out', top='off', right='off')

# format of the labels
hfmt = dates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(hfmt)
fig.autofmt_xdate(rotation=90, ha='center')

#---- set axes labels ----

ax.set_ylabel('Number of tasks', labelpad=10, fontsize=14)
ax.set_xlabel('Time', labelpad=20, fontsize=14)

#---- plot data ----

ax.plot(t, x, color="#004c99", label="Number of Tasks")
ax.fill_between(t, x, 0, facecolor='#00a1e4', alpha=0.5, lw=0.5)

#---- set axis limits ----

timemin = datetime.datetime(2015, 1, 1, 0)
timemax = datetime.datetime(2015, 1, 1, 12)

ax.axis(xmin=timemin, xmax=timemax)

plt.show()  

导致:

enter image description here