matplotlib中x轴的良好日期格式

3
我有以下数据框:
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:00,并将您的线发送回绘图的起点。 - xnx
1个回答

7

plt.fill 基本上将时间序列的第一个点和最后一个点连接起来以构建其多边形。我建议使用fill_between

下面是一个 MWE,展示了如何实现此操作。它还展示了一种格式化 x 轴标签的方法,该方法源自以下帖子:在 Matplotlib 中创建带有日期和时间的轴标签的图表在 Python 中使用 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


很棒的解释和帮助!谢谢! - F1990
@F1990 很棒。我已更新示例,现在还可以控制坐标轴限制。时间现在一直持续到12:00,而不仅仅是11:30。 - Jean-Sébastien
太好了,我打算在我的代码中实现它。也许你还知道一个好的解决方案来回答我的另一个问题吗?https://dev59.com/d43da4cB1Zd3GeqP1IV9 - F1990

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接