matplotlib 字符串转日期

3 投票
4 回答
17568 浏览
提问于 2025-04-18 06:29

你好,我正在尝试把一串日期(以字符串形式)转换成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这样的格式。

4 个回答

0

最简单的方法就是直接使用numpy:


import matplotlib
from matplotlib import pyplot
from matplotlib import dates
import numpy as np

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']

converted_dates = np.array(dates, dtype='datetime64[ms]')

ydata = range(0,8)
pyplot.plot(converted_dates, ydata, '-' )
pyplot.show()
0

试试用 strptime 这个方法。相关的说明文档在这里:

https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

举个例子:

import datetime
sDate = '2014-05-06'
dtDate = datetime.datetime.strptime(sDate,"%m-%d-%Y")

matplotlib 可以比较日期时间对象。

4

使用 matplotlib.dates.datestr2num 这个方法的想法在原则上是对的。接下来,你需要告诉 matplotlib 实际上把得到的数字当作日期来理解。一个简单的选择是用 plot_date 来代替 plot

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

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']

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

y_axis = range(0,8)
plt.plot_date( x_axis, y_axis, '-' )

plt.show()
8

这是目标吗?(提到旋转是因为它几乎总是和日期相关。)

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

在这里输入图片描述

撰写回答