python中输入17=x会引起错误,使用matplotlib和datetime在Python中格式化日期:x轴错误-浮点数...

I try to plot a graph with a set of data. The y-axis is no problem, it's simple floats.

Problem is the x-axis: Its data is formatted by datetime to '%Y-%m-%d %H:%M:%S'. When trying to plot it occurs of course the error of no float possible... I tried quite many ways and it still wouldn't work...

So input so far are two arrays: x is ['2016-02-05 17:14:55', '2016-02-05 17:14:51', '2016-02-05 17:14:49', ...]. y is ['35.764299', '20.3008', '36.94704', ...]

解决方案

You could use the DateFormatter as follows:

import matplotlib

import matplotlib.pyplot as plt

from datetime import datetime

x_orig = ['2016-02-05 17:14:55', '2016-02-05 17:14:51', '2016-02-05 17:14:49']

x = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x_orig]

y = ['35.764299', '20.3008', '36.94704']

xs = matplotlib.dates.date2num(x)

hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')

fig = plt.figure()

ax = fig.add_subplot(1,1,1)

ax.xaxis.set_major_formatter(hfmt)

plt.setp(ax.get_xticklabels(), rotation=15)

ax.plot(xs, y)

plt.show()

This would display the following:

424ae75a9e36e67cfa6200f6b2178fe2.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值