2015-01-21 125 views
2

我在下面寫了一個簡單的腳本來用matplotlib生成一個圖。我想將x-tick頻率從每月增加到每週並旋轉標籤。我不知道從哪裏開始使用x軸頻率。我的旋轉線產生一個錯誤:TypeError: set_xticks() got an unexpected keyword argument 'rotation'。對於旋轉,我不希望使用plt.xticks(rotation=70),因爲我最終可能會在多個子圖中構建,其中一些應該有一個旋轉的軸,一些不應該。Matplotlib中x軸標籤的頻率和旋轉

import datetime 
import matplotlib 
import matplotlib.pyplot as plt 
from datetime import date, datetime, timedelta 

def date_increments(start, end, delta): 
    curr = start 
    while curr <= end: 
     yield curr 
     curr += delta 

x_values = [[res] for res in date_increments(date(2014, 1, 1), date(2014, 12, 31), timedelta(days=1))] 
print len(x_values) 
y_values = [x**2 for x in range(len(x_values))] 
print len(y_values) 
fig = plt.figure() 

ax = fig.add_subplot(111) 
ax.plot(x_values, y_values) 
ax.set_xticks(rotation=70) 
plt.show() 

回答

4

看一看matplotlib.dates,特別是在this example

蜱頻率

你可能會想要做這樣的事情:

from matplotlib.dates import DateFormatter, DayLocator, MonthLocator 
days = DayLocator() 
months = MonthLocator() 

months_f = DateFormatter('%m') 

ax.xaxis.set_major_locator(months) 
ax.xaxis.set_minor_locator(days) 
ax.xaxis.set_major_formatter(months_f) 

ax.xaxis_date() 

這將繪製天輕微蜱個月主要蜱,標有月份數。

標籤

的旋轉可以使用plt.setp()分別更改軸:

plt.setp(ax.get_xticklabels(), rotation=70, horizontalalignment='right') 

希望這有助於。