通過搜索« python matplotlib在搜索引擎上使用日期作爲xlabel»,你可以在Matplotlib文檔中找到你想要的例子:https://matplotlib.org/examples/api/date_demo.html。
這個例子假設你的xdata是日期,但現在情況並非如此。您需要創建日期的列表並使用的,而不是你的範圍(48 * 58)名單,像這樣:
import pandas
xdata = pandas.date_range(
pandas.to_datetime("2008-01-01"),
pandas.to_datetime("2008-02-27 23:30:00"),
freq=pandas.to_timedelta(30,unit="m")).tolist()
這從開始時間的頻率創建日期時間的列表,你的結束時間30分鐘。
之後,您需要使用上面鏈接中的示例。在這裏它被複制和調整了一下你的需求,但你需要玩弄它來適當地設置它。您可以在matplotlib中找到更多使用日期的示例,現在您將使用日期列表作爲您的繪圖的輸入。
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
# define locators for every month and every day
months = mdates.MonthLocator() # every month
days = mdates.DayLocator() # every day
monthsFmt = mdates.DateFormatter('%m')
# create the plot and plot your data
fig, ax = plt.subplots()
ax.plot(xdata, week.LoadNette)
# format the x ticks to have a major tick every month and a minor every day
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
ax.xaxis.set_minor_locator(days)
# format the xlabel to only show the month
ax.format_xdata = mdates.DateFormatter('%m')
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
在Matplotlib使用日期很嚇人,但它的不只是黑客你想這個特定的時間標籤從長遠來看更好。