Skip to main content
 首页 » 编程设计

python之matplotlib 字符串到日期

2025年05月04日2952php

您好,我正在尝试将日期列表作为字符串转换为 matplotlib 中的 x 轴,但我似乎无法将其正确输出。

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 等

请您参考如下方法:

这是目标吗? (轮流抛出,因为它几乎总是出现,带有日期。)

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()