2013-07-03 25 views
2

看看這個例子:不是寫出來的所有日期的軸線上,Matplotlib

import datetime as dt 
from matplotlib import pyplot as plt 
import matplotlib.dates as mdates 
x = [] 
d = dt.datetime(2013, 7, 4) 
for i in range(30): 
     d = d+dt.timedelta(days=1) 
     x.append(d) 

y = range(len(x)) 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator()) 
plt.gcf().autofmt_xdate() 
plt.bar(x,y) 
plt.show() 

代碼寫出日期在x軸的情節,見下圖。問題在於日期堵塞了,如圖所示。如何讓matplotlib只寫出每五分之一或每十分之一的座標?

enter image description here

+0

關於旋轉日期標註90度是什麼? 'plt.xticks(旋轉= 90)'。 – wflynny

回答

5

您可以指定一個interval參數的DateLocator如以下。例如, interval=5定位器每隔5天放置一次滴答。另外,將autofmt_xdate()放在bar方法後面以獲得所需的輸出。

import datetime as dt 
from matplotlib import pyplot as plt 
import matplotlib.dates as mdates 
x = [] 
d = dt.datetime(2013, 7, 4) 
for i in range(30): 
     d = d+dt.timedelta(days=1) 
     x.append(d) 

y = range(len(x)) 
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5)) 
plt.bar(x, y, align='center') # center the bars on their x-values 
plt.title('DateLocator with interval=5') 
plt.gcf().autofmt_xdate() 
plt.show() 

Bar plot with ticks at every 5th date.

隨着interval=3你會得到一個刻度爲每3日期:

Bar plot with ticks at every 3rd date.

相關問題