Tom*_*Cho 6 python datetime matplotlib
我试图datetime用pyplot对x轴上的对象列表绘制一些数据.但是日期显示为标准格式,%Y-%m-%d %H:%M:%S(太长).我可以通过创建日期字符串列表来避免这种情况,strftime并使用它来代替.我也知道有一些date内在的对象pyplot我可以使用而不是datetime.
有没有办法告诉pyplot以哪种格式绘制datetime对象?无需将所有内容转换为字符串或其他类型的对象?
谢谢.
Imp*_*est 12
除了如其他答案中所示手动指定轴的日期时间格式外,您还可以使用rcParams来设置格式。
标准是
Run Code Online (Sandbox Code Playgroud)# date.autoformatter.year : %Y # date.autoformatter.month : %Y-%m # date.autoformatter.day : %Y-%m-%d # date.autoformatter.hour : %m-%d %H # date.autoformatter.minute : %d %H:%M # date.autoformatter.second : %H:%M:%S # date.autoformatter.microsecond : %M:%S.%f
您可以在matplotlib rc 文件中
或在代码中通过
plt.rcParams["date.autoformatter.minute"] = "%Y-%m-%d %H:%M:%S"
Run Code Online (Sandbox Code Playgroud)
你可以使用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()
Run Code Online (Sandbox Code Playgroud)