2015-12-13 75 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