[英]Custom date range (x-axis) in time series with matplotlib
我繪制時間序列的代碼是這樣的:
def plot_series(x, y):
fig, ax = plt.subplots()
ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers
fig.autofmt_xdate()
plt.grid(True)
plt.show()
我有幾千個數據點,所以matplotlib創建3個月的x軸范圍。 這是我的時間序列現在的樣子:
但是,我希望每周一次/每兩周一次。 如何更改matplotlib計算x軸日期范圍的方式,由於我有近1年的數據,如何確保所有數據都能很好地適用於單個圖表?
要更改x軸上刻度線的頻率,必須設置其定位器。
要為每周的每個星期一打勾,您可以使用matplotlib的dates
模塊提供的WeekdayLocator
。
(未經測試的代碼) :
from matplotlib.dates import WeekdayLocator
def plot_series(x, y):
fig, ax = plt.subplots()
ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers
fig.autofmt_xdate()
# For tickmarks and ticklabels every week
ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO))
# For tickmarks and ticklabels every other week
#ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=2))
plt.grid(True)
plt.show()
當僅使用一個圖時,這可能在x軸上有點擁擠,因為這會產生大約52個刻度。
一個可能的解決方法是每隔n周(例如每4周)進行一次滴答標記,並且每周只有標記(即沒有標記標記):
from matplotlib.dates import WeekdayLocator
def plot_series(x, y):
fig, ax = plt.subplots()
ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers
fig.autofmt_xdate()
# For tickmarks and ticklabels every fourth week
ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=4))
# For tickmarks (no ticklabel) every week
ax.xaxis.set_minor_locator(WeekdayLocator(byweekday=MO))
# Grid for both major and minor ticks
plt.grid(True, which='both')
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.