2017-01-26 117 views
0

使用numpy的指數的日期我有一個numpy的陣列看起來像這樣:在matplotlib

       Close 
Date        
2016-12-22     11.43 
2016-12-23     11.44 
2016-12-27     11.99 
2016-12-28     12.95 
2016-12-29     13.37 

我只想要日期,而不是一個月或一年,並在matplotlib圖用它作爲X軸。

我用

np.index.day 

提取日期。結果如下所示:

plt.xlim(NP,5)

I:

[22 23 27 28 29]

但是當我在將它們用於X軸得到ValueError:具有多個元素的數組的真值是不明確的。使用a.any()或a.all()。 np.tolist()沒有幫助。什麼會使這項工作?

回答

0

如果我正確理解你的問題,你想從你的數組中提取日子,然後相應地設置圖的x極限。你可以這樣做:

limits = np.index.day 
plt.xlim(limits[0], limits[-1]) 

你行plt.xlim(np, 5)沒有任何意義,因爲你通過np模塊和作爲參數傳遞給xlim()整數5

plt.xlim()接受x軸上最小和最大限制的數值(請參閱docs)。在上面的例子中,我們從numpy數組中得到日期,並將結果數組的第一個元素設置爲最小x值,將最後一個元素設置爲最大x值。


更新26/01/20174:如果你想繪製跨多個月的日期範圍

,這將是更好地使用相應的datetime對象,並相應地格式化x軸。

我將構造一個簡單的例子,曲線數據從2016年12月29日到2017年1月2日:

import pandas as pd 
import matplotlib.pyplot as plt 

from matplotlib.dates import DayLocator, DateFormatter 

a = pd.DataFrame.from_dict({'Date': pd.date_range('2016-12-29', '2017-01-02'), 'Close': (11.43, 11.44, 11.99, 12.95, 13.37)}).set_index('Date') 
print(a) 

days = DayLocator() 
daysFmt = DateFormatter('%d') 

fig, ax = plt.subplots() 

ax.plot_date(a.index, a.Close) 
ax.xaxis.set_major_locator(days) 
ax.xaxis.set_major_formatter(daysFmt) 

plt.show() 

結果:

  Close 
Date 
2016-12-29 11.43 
2016-12-30 11.44 
2016-12-31 11.99 
2017-01-01 12.95 
2017-01-02 13.37 

enter image description here

+0

我試圖PLT。 xlim(限制[0],限制[-1]),但不能繪製任何線條。只是X-Y軸。而X軸只能從22到23. – slard

+0

我想我明白爲什麼這不起作用。因爲他們是日期,他們每個月都會開始。所以如果上面的數組包含2017-1-1,那麼X軸會認爲你從22數到1. – slard

+0

我已經用一個繪製跨多個月的數據的例子更新了我的答案。我希望現在能回答你的問題。 – Milo