分析美国总统历年在国情咨文中对国会提起的诉讼数量

给出数据集的网址:http://www.presidency.ucsb.edu/data/sourequests.php


In [6]:
import numpy as np
from matplotlib.pylab import frange
import matplotlib.pyplot as plt

fill_data = lambda x:int(x.strip() or 0)
data = np.genfromtxt('president.txt',dtype=(int,int),converters={1:fill_data},delimiter=',')
x = data[:,0]
y = data[:,1]

In [9]:
# 绘制数据图形以观察趋势
plt.close('all')
plt.figure(1)
plt.title('All data')
# 红色 点
plt.plot(x,y,'or')
plt.xlabel('year')
plt.ylabel('No Presndential Request')
plt.show()



In [10]:
# 绘制数据图形以观察趋势
plt.close('all')
plt.figure(1)
plt.title('All data')
# 红色 折线
plt.plot(x,y,'r')
plt.xlabel('year')
plt.ylabel('No Presndential Request')
plt.show()


计算百分位数,来了解数据的参考


In [11]:
perc_25 = np.percentile(y,25)
perc_50 = np.percentile(y,50)
perc_75 = np.percentile(y,75)

print '25th Percentile = %0.2f' % (perc_25)
print '50th Percentile = %0.2f' % (perc_50)
print '75th Percentile = %0.2f' % (perc_75)


25th Percentile = 13.00
50th Percentile = 18.50
75th Percentile = 25.25

In [13]:
# 将这些百分位数添加到之前生成的图形
# 绘制数据图形以观察趋势
plt.close('all')
plt.figure(1)
plt.title('All data')
# 红色 折线
plt.plot(x,y,'or')
plt.xlabel('year')
plt.ylabel('No Presndential Request')
plt.axhline(perc_25,label='25th perc',c='r')
plt.axhline(perc_50,label='50th perc',c='g')
plt.axhline(perc_75,label='75th perc',c='b')
plt.legend(loc='best')
plt.show()


在图形中检查是否存在异常点
使用mask函数删除异常点
删除异常点最小的0 最大值 54


In [15]:
y_masked = np.ma.masked_where(y==0,y)
y_masked = np.ma.masked_where(y_masked==54,y_masked)

In [16]:
# 删除异常点后重新绘图
plt.figure(2)
plt.title('Masked data')
plt.plot(x,y,'or')
plt.xlabel('year')
plt.ylabel('No presedential Request')
plt.ylim(0,60)

# 绘制
plt.axhline(perc_25,label='25th perc',c='r')
plt.axhline(perc_50,label='50th perc',c='g')
plt.axhline(perc_75,label='75th perc',c='m')
plt.legend(loc='best')
plt.show()