简体   繁体   English

使用matplotlib绘制图形时,在光标位置看不到日期/时间。 出现错误,如“ DateFormatter找到x = 0的值”

[英]can't see Date/Time in the cursor position while plotting a graph with matplotlib. Getting error as “DateFormatter found a value of x=0”

I have a timestamp list like: 我有一个时间戳列表,例如:

['2018-06-28 20:00:00', '2018-06-28 20:00:05', '2018-06-28 20:00:10', '2018-06-28 20:00:15', '2018-06-28 20:00:20', '2018-06-28 20:05:30']

I am plotting graph like this, where timestamp and iops is a list like: 我正在绘制这样的图形,其中timestamp和iops是这样的列表:

p1, = host.plot(timestamp[0:], iops[0:], "b-", label="IOPS")

I have set x_lim as: 我将x_lim设置为:

host.set_xlim([timestamp[0],timestamp[-1]])

This is what i have done to show timestamp on x axis: 这是我在x轴上显示时间戳的方法:

_fmt = mdates.DateFormatter('%Y-%m-%d')
_fmt.format_data_short = lambda pos: mdates.num2date(pos).strftime("%Y-%m-%d; %H:%M:%S")
 host.xaxis.set_major_formatter(_fmt)

The full error message reads 完整的错误消息显示为

ValueError: DateFormatter found a value of x=0, which is an illegal date. ValueError:DateFormatter发现x = 0的值,这是一个非法日期。 This usually occurs because you have not informed the axis that it is plotting dates, eg, with ax.xaxis_date() 通常发生这种情况是因为您尚未通知轴它正在绘制日期,例如,使用ax.xaxis_date()

And that is true indeed, because you are plotting strings here and matplotlib cannot know that they carry a meaning as "date" for you. 的确如此,因为您在此处绘制字符串,而matplotlib无法知道它们对您而言具有“日期”的含义。

The solution is to convert them to dates. 解决方案是将它们转换为日期。

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

timestamp= ['2018-06-28 20:00:00', '2018-06-28 20:00:05', '2018-06-28 20:00:10', 
            '2018-06-28 20:00:15', '2018-06-28 20:00:20', '2018-06-28 20:05:30']
dates = [datetime.strptime(t, "%Y-%m-%d %H:%M:%S") for t in timestamp]
y = list(range(6))

fig, ax = plt.subplots()
p1, = ax.plot(dates, y, "b-", label="IOPS")

ax.set_xlim([dates[0],dates[-1]])

_fmt = mdates.DateFormatter('%Y-%m-%d')
_fmt.format_data_short = lambda pos: mdates.num2date(pos).strftime("%Y-%m-%d; %H:%M:%S")
ax.xaxis.set_major_formatter(_fmt)

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM