2015-04-30 112 views
1

我想用pyplot在x軸上繪製一些數據與datetime對象的列表。但日期顯示爲標準格式,即%Y-%m-%d %H:%M:%S(太長)。我可以通過創建一個包含strftime的日期字符串列表來避免這種情況,並使用它。我也知道pyplot有一些date固有的物體,我可以用它代替datetimepyplot軸中日期時間的格式

有沒有辦法告訴pyplot以哪種格式繪製datetime對象?無需將所有內容轉換爲字符串或其他類型的對象?

謝謝。

回答

2

您可以使用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() 
0

除手動指定日期時間格式軸,如圖the other answer,你可以使用rcParams來設置格式。

標準是

# 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 file
或經由

plt.rcParams["date.autoformatter.minute"] = "%Y-%m-%d %H:%M:%S" 
裏面的代碼