本文介绍了pyplot轴中日期时间的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用pyplot在x轴上的datetime对象列表上绘制一些数据.但是,日期显示为标准格式,即%Y-%m-%d %H:%M:%S(太长).我可以通过使用strftime创建日期字符串列表来规避此问题,而改用它.我也知道,对于pyplot,存在某种date对象固有的对象,我可以使用它代替datetime.

I am trying to plot some data against a list of datetime objects in the x axis with pyplot. However the dates appear as the standard format, which is %Y-%m-%d %H:%M:%S (way too long). I can circumvent this by creating a list of date strings with strftime and use that instead. I also know that there is some kind of date object intrinsic for pyplot which I could use instead of datetime.

有没有办法告诉pyplot以哪种格式绘制datetime对象?不必将所有内容都转换为字符串或其他类型的对象?

Is there a way to tell pyplot in which format to plot the datetimeobjects however? Without having to transform everything to string or another kind of object?

谢谢.

推荐答案

您可以使用DateFormatter:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(your_dates, your_data)

# format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate and align the tick labels so they look better
fig.autofmt_xdate()

这篇关于pyplot轴中日期时间的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 22:46