2013-09-01 1 views
0

следующих строк:Mofifying X-ось блок на Python графы

import Quandl 
import datetime 
import matplotlib.pyplot as plt 

# Import data from Quandl 
DJI = Quandl.get("WREN/W6", trim_start="1980-01-01", trim_end= datetime.date.today()) 

''' 
type(DJI) => class 'pandas.core.frame.DataFrame' 
''' 

# Plot DJI 
DJI.plot() 
plt.show() 

Производить эту схему:

enter image description here

Как я могу установить основной блок таким образом, что каждый год с самого начала конец моей серии читается и читается только один раз?

Возможно использование функций MultipleLocator и FormatStrFormatter? Но как это работает с датами? Длина моего временного ряда меня различна.

+0

Вы хотите показать каждый год на оси х ? –

+0

да, это то, что мой blabla выше пытается сказать – tagoma

ответ

2

Вы можете использовать YearLocator от модуля matplotlib dates.

from matplotlib.dates import YearLocator, DateFormatter 

... 

# YearLocator defaults to a locator at 1st of January every year 
plt.gca().xaxis.set_major_locator(YearLocator()) 

plt.gca().xaxis.set_major_formatter(DateFormatter('%Y')) 
+0

thx. И какой трюк теперь, если я хочу, чтобы ось х читала 1 год старше 2 (1980, 1982, 1984, ...) против каждого года (1980, 1981, ...) ??? – tagoma

+0

Я не уверен, что понимаю, что вы имеете в виду. Если вы хотите галочку на каждый другой год (1980, 1982, 1984), вы можете указать это с помощью «YearLocator (base = 2)». – hooy

2

Вам нужно на самом деле назвать plt.plot (или использовать matplotlib API), поскольку Matplotlib не корректно отобразить datetime64 массивы на оси х. Например:

In [18]: s = Series(randn(10), index=date_range('1/1/2001', '1/1/2011', freq='A')) 

In [19]: s 
Out[19]: 
2001-12-31 -1.236 
2002-12-31 0.234 
2003-12-31 -0.858 
2004-12-31 -0.472 
2005-12-31 1.186 
2006-12-31 1.476 
2007-12-31 0.212 
2008-12-31 0.854 
2009-12-31 -0.697 
2010-12-31 -1.241 
Freq: A-DEC, dtype: float64 

In [22]: ax = s.plot() 

In [23]: ax.xaxis.set_major_locator(YearLocator()) 

In [24]: ax.xaxis.set_major_formatter(DateFormatter('%Y')) 

дает

enter image description here

Вместо этого вы должны сделать что-то вроде:

fig, ax = subplots() 
ax.plot(s.index.to_pydatetime(), s.values) 
ax.xaxis.set_major_locator(YearLocator()) 
ax.xaxis.set_major_formatter(DateFormatter('%Y')) 
fig.autofmt_xdate() 

получить:

enter image description here

Если вы хотите различный год кратные, пройти мультипликатор вы хотите к YearLocator конструктора, например:

fig, ax = subplots() 
ax.plot(s.index.to_pydatetime(), s.values) 
ax.xaxis.set_major_locator(YearLocator(2)) 
ax.xaxis.set_major_formatter(DateFormatter('%Y')) 
fig.autofmt_xdate() 

в результате:

enter image description here

Смежные вопросы