2015-01-21 133 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') 

希望这有助于。