Matplotlib y 轴上的日期

Arn*_*rne 7 datetime matplotlib

我试图在 matplotlib 中绘制一系列日落时间,但出现以下错误:“TypeError: Empty 'DataFrame': no numeric data toplot”

我已经查看了几个要转换的选项,例如 plt.dates.date2num 但这并不能真正满足我的需求,因为我想以可读格式(即时间)绘制它。我发现的所有示例在 x 轴上都有时间,但在 y 轴上没有时间。

难道就没有办法完成这个任务吗?有人有主意吗?

我非常期待您的回复。最好的问候,阿恩

3 Jan 2013          16:44:00
4 Jan 2013          16:45:00
5 Jan 2013          16:46:00
6 Jan 2013          16:47:00
7 Jan 2013          16:48:00
8 Jan 2013          16:49:00
9 Jan 2013          16:51:00
10 Jan 2013         16:52:00
11 Jan 2013         16:53:00
12 Jan 2013         16:55:00
13 Jan 2013         16:56:00
14 Jan 2013         16:57:00
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 7

如果您尝试在 x 轴上绘制一些未指定的数据,在 y 轴上绘制日期/时间,或者您尝试在 x 轴上绘制天数,在 y 轴上绘制时间,那么您的问题并不清楚-轴。

不过,从你的问题来看,我假设是后者。

听起来您可能正在使用pandas,但目前,我假设您有两个字符串序列:一个包含日期,另一个包含时间序列。

要将给定轴视为日期,只需调用ax.xaxis_date()ax.yaxis_date()。在这种情况下,两者实际上都是日期。(《泰晤士报》将把今天作为这一天,尽管您不会直接看到这一点。)

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013', '7 Jan 2013',
        '8 Jan 2013', '9 Jan 2013', '10 Jan 2013', '11 Jan 2013', '12 Jan 2013',
        '13 Jan 2013', '14 Jan 2013']
time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00', '16:49:00',
        '16:51:00', '16:52:00', '16:53:00', '16:55:00', '16:56:00', '16:57:00']

# Convert to matplotlib's internal date format.
x = mdates.datestr2num(date)
y = mdates.datestr2num(time)

fig, ax = plt.subplots()

ax.plot(x, y, 'ro-')
ax.yaxis_date()
ax.xaxis_date()

# Optional. Just rotates x-ticklabels in this case.
fig.autofmt_xdate()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述