matplotlib字符串到日期 [英] matplotlib string to dates

查看:59
本文介绍了matplotlib字符串到日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期列表作为字符串转换为matplotlib中的x轴,但似乎无法正确显示出来.

Hi I am trying to convert a list of dates as strings to an x axis in matplotlib and I can't seem to get it to come out right.

dates =  ['2014-05-06', '2014-05-07', '2014-05-08', '2014-05-09', '2014-05-10', '2014-05-11', '2014-05-12', '2014-05-13']

import matplotlib
from matplotlib import pyplot
from matplotlib import dates

converted_dates = matplotlib.dates.datestr2num(dates)
x_axis = (converted_dates)

y_axis = range(0,8)
pyplot.plot( x_axis, y_axis, '-' )
pyplot.show()

这使图表的x轴返回1 2 3 4 5 6 7,这是我所缺少的.我想显示2014-05-06等

This brings back 1 2 3 4 5 6 7 on the x axis on the chart, what am I missing. I would like this to display 2014-05-06 etc

推荐答案

这是目标吗? (旋转,因为它几乎总是与日期一起出现.)

Is this the goal? (Threw in rotation because it almost always comes up, with dates.)

datelist =  ['2014-05-06', '2014-05-07', '2014-05-08', '2014-05-09', '2014-05-10',    '2014-05-11', '2014-05-12', '2014-05-13']

import matplotlib
from matplotlib import pyplot
from matplotlib import dates
import datetime

converted_dates = list(map(datetime.datetime.strptime, datelist, len(datelist)*['%Y-%m-%d']))
x_axis = converted_dates
formatter = dates.DateFormatter('%Y-%m-%d')


y_axis = range(0,8)
pyplot.plot( x_axis, y_axis, '-' )
ax = pyplot.gcf().axes[0] 
ax.xaxis.set_major_formatter(formatter)
pyplot.gcf().autofmt_xdate(rotation=25)
pyplot.show()

这篇关于matplotlib字符串到日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆