2015-12-13 168 views
0

我已經用matplotlib編寫了下面的程序,用於隨時間繪製no.of個元素。python matplotlib設置x軸的年數

import pylab 
import numpy as np 
import datetime 
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter 

date1 = datetime.date(1995, 1, 1) 
date2 = datetime.date(2004, 4, 12) 

years = YearLocator() # every year 
months = MonthLocator() # every month 
yearsFmt = DateFormatter('%Y') 

ax.xaxis.set_major_locator(years) 
ax.xaxis.set_major_formatter(yearsFmt) 
ax.xaxis.set_minor_locator(months) 
ax.autoscale_view() 

pylab.ylim(0, 250) 
plt.yticks(np.linspace(0,250,6,endpoint=True)) 

pylab.xlabel('YEAR') 
pylab.ylabel('No. of sunspots') 
pylab.title('SUNSPOT VS YEAR GRAPH') 

a=[[50,50],[100,100],[250, 250],[200,200],[150,150]] 
plt.plot(*zip(*a), marker='o', color='r', ls='') 

的輸出是如下

enter image description here

然而,我期待它顯示年,而不是號碼x軸。

+0

對於日期定位器/格式化才能正常工作,你需要暗算'datetime'對象。 – tacaswell

回答

3

繪製年,但年50,100,250,200,和150。這些是在列表中的a內側的第一元件,其被傳遞到pyplot.plot作爲x值。

你想在某個地方定義你的日期,儘管你也可能想要將xticks設置爲與你繪製的日期相同,因爲我可以告訴你關於看起來整潔的圖。

import pylab 
import numpy as np 
import datetime 
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter 

另外,不要忘記導入pyplot

import matplotlib.pyplot as plt 

這裏有一些例子日期。您可以將它們更改爲針對太陽黑子測量的具體日期。

a=[[datetime.date(1995, 1, 1), 50], 
    [datetime.date(2000, 1, 1), 100], 
    [datetime.date(2005, 1, 1), 250], 
    [datetime.date(2010, 1, 1), 200], 
    [datetime.date(2015, 1, 1), 150] 
    ] 

years = YearLocator() # every year 
months = MonthLocator() # every month 
yearsFmt = DateFormatter('%Y') 

調用gca在修改軸之前獲取當前座標軸。

ax = plt.gca() 
ax.xaxis.set_major_locator(years) 
ax.xaxis.set_major_formatter(yearsFmt) 
ax.xaxis.set_minor_locator(months) 
ax.autoscale_view() 

pylab.ylim(0, 250) 
plt.yticks(np.linspace(0,250,6,endpoint=True)) 

a數組中挑選日期以將它們用作xtick標籤。

dates = [date for date,sunspot in a] 
plt.xticks(dates) 

pylab.xlabel('YEAR') 
pylab.ylabel('No. of sunspots') 
pylab.title('SUNSPOT VS YEAR GRAPH') 

plt.plot(*zip(*a), marker='o', color='r', ls='') 
plt.show() 

pyplot output