Introduction
Table des matières
Exemple
#!/usr/bin/env python
'''
Copyright (c) 2013 Marchant Benjamin
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
from scipy import stats
from scipy.stats import pearsonr
import numpy as np
import matplotlib.pyplot as plt
import math
from numpy import *
import matplotlib
import xlrd
# '---------- Read a XLS (Excel) File ----------'
#Taille, Poids = np.loadtxt("data.txt", unpack=True, skiprows=1)
workbook = xlrd.open_workbook('comp_pop_tests_parametriques.xls')
SheetNameList = workbook.sheet_names()
for i in np.arange( len(SheetNameList) ):
print SheetNameList[i]
worksheet = workbook.sheet_by_name('dataset')
num_rows = worksheet.nrows
num_cells = worksheet.ncols
print 'num_rows, num_cells', num_rows, num_cells
DataArray = np.empty((num_rows,num_cells), dtype="|S16")
curr_row = 0
while curr_row < num_rows:
row = worksheet.row(curr_row)
#print row, len(row), row[0], row[1]
#print 'Row: ', curr_row
#print row, len(row), row[0]
curr_cell = 0
while curr_cell < num_cells:
# Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
cell_type = worksheet.cell_type(curr_row, curr_cell)
cell_value = worksheet.cell_value(curr_row, curr_cell)
#print ' ', cell_type, ':', cell_value
if cell_type == 2:
DataArray[curr_row,curr_cell] = str(cell_value)
if cell_type == 1:
DataArray[curr_row,curr_cell] = cell_value
curr_cell += 1
curr_row += 1
#print DataArray
#print DataArray[:,1]
#print DataArray.shape
ArrayShape = DataArray.shape
# '---------- Print Descriptive statistics: Continuous Case ----------'
class DescriptiveStatisticsParameters():
def createParameters(self,Data):
self.DataValue = np.zeros(1)
self.DataValue = Data
self.Mean = np.mean(Data)
self.MinValue = min(Data)
self.MaxValue = max(Data)
self.NbData = Data.shape[0]
self.NbClass = int( math.log(self.NbData,2) ) + 1
self.Range = max(Data) - min(Data)
self.ClassRange = float(self.Range)/self.NbClass
self.X = np.arange(self.NbClass)
self.AbsoluteFrequency = np.zeros(self.NbClass)
for i in np.arange(self.NbData):
c = int((Data[i]-min(Data))/self.ClassRange)
if c >= self.NbClass:
c = self.NbClass - 1
self.AbsoluteFrequency[c] = self.AbsoluteFrequency[c] + 1
ClassLabel = []
j = round(min(Data),2)
for i in np.arange(self.NbClass+1):
ClassLabel.append(j)
j = round(j + self.ClassRange,2)
self.LabelList = (ClassLabel)
self.x_pos = np.arange(len(self.LabelList))
def create2d(self,Data_01,Data_02):
self.Contingency = np.zeros((first.NbClass,second.NbClass))
for i in np.arange(self.NbData):
ni = int((Data_01[i]-min(Data_01))/first.ClassRange)
nj = int((Data_02[i]-min(Data_02))/second.ClassRange)
if ni >= first.NbClass:
ni = first.NbClass - 1
if nj >= second.NbClass:
nj = second.NbClass - 1
self.Contingency[ni,nj] = self.Contingency[ni,nj] + 1
# '---------- Print Descriptive statistics: Continuous Case ----------'
SelectedColumn = np.zeros(ArrayShape[0]-1)
#data = DataArray[:,1]
for i in np.arange(ArrayShape[0]):
if i > 0:
SelectedColumn[i-1] = DataArray[i,1]
print SelectedColumn
print SelectedColumn.shape
MaleSalary = DescriptiveStatisticsParameters()
MaleSalary.createParameters(SelectedColumn)
SelectedColumn = np.zeros(ArrayShape[0]-1)
#data = DataArray[:,1]
for i in np.arange(ArrayShape[0]):
if i > 0:
SelectedColumn[i-1] = DataArray[i,2]
print SelectedColumn
print SelectedColumn.shape
FemaleSalary = DescriptiveStatisticsParameters()
FemaleSalary.createParameters(SelectedColumn)
print 'Mean (Male Salry)', MaleSalary.Mean
print 'Mean (Female Salary)', FemaleSalary.Mean
print 'Covariance (Male-Female Salary) unbiased', np.cov(MaleSalary.DataValue,FemaleSalary.DataValue, ddof=1)
print 'Covariance (Male-Female Salary) biased', np.cov(MaleSalary.DataValue,FemaleSalary.DataValue, ddof=0)
#print FemaleSalary.DataValue
r_row, p_value = pearsonr(MaleSalary.DataValue,FemaleSalary.DataValue)
print 'pearsonr', r_row, p_value
fig = plt.figure()
plt.xlim(MaleSalary.MinValue,MaleSalary.MaxValue)
plt.ylim(FemaleSalary.MinValue,FemaleSalary.MaxValue)
plt.xlabel('Male Salary')
plt.ylabel('Female Salary')
plt.scatter(MaleSalary.DataValue, FemaleSalary.DataValue, s=80, facecolors='none', edgecolors='r')
plt.plot([MaleSalary.Mean,MaleSalary.Mean],[FemaleSalary.MinValue,FemaleSalary.MaxValue], 'r--')
plt.plot([MaleSalary.MinValue,MaleSalary.MaxValue],[FemaleSalary.Mean,FemaleSalary.Mean], 'r--')
plt.savefig('ScatterPlot.png', bbox_inches='tight')
plt.show()
fig = plt.figure()
plt.xticks(MaleSalary.x_pos, MaleSalary.LabelList,rotation=45)
plt.ylabel(r'Absolute Frequency $n_i$')
bar1 = plt.bar(MaleSalary.X,MaleSalary.AbsoluteFrequency,\
width=1.0,bottom=0,color='Green',alpha=0.65,label='Legend')
plt.savefig('HistogramMaleSalary.png', bbox_inches='tight')
plt.show()
fig = plt.figure()
plt.xticks(FemaleSalary.x_pos, FemaleSalary.LabelList,rotation=45)
plt.ylabel(r'Absolute Frequency $n_i$')
bar1 = plt.bar(FemaleSalary.X,FemaleSalary.AbsoluteFrequency,\
width=1.0,bottom=0,color='Green',alpha=0.65,label='Legend')
plt.savefig('HistogramFemaleSalary.png', bbox_inches='tight')
plt.show()
# '---------- Kernel Plot ----------'
# '---------- Contingency Plot ----------'
#first.create2d(Taille,Poids)
#first.Contingency = first.Contingency * 100.0 / first.NbData
ContingencyTable = np.zeros((MaleSalary.NbClass,FemaleSalary.NbClass))
for i in np.arange(MaleSalary.NbData):
ni = int((MaleSalary.DataValue[i]-MaleSalary.MinValue)/MaleSalary.ClassRange)
nj = int((FemaleSalary.DataValue[i]-FemaleSalary.MinValue)/FemaleSalary.ClassRange)
if ni >= MaleSalary.NbClass:
ni = MaleSalary.NbClass - 1
if nj >= FemaleSalary.NbClass:
nj = FemaleSalary.NbClass - 1
ContingencyTable[ni,nj] = ContingencyTable[ni,nj] + 1
ContingencyTable = ContingencyTable * 100.0 / MaleSalary.NbData
#print ContingencyTable
#print ContingencyTable.max()
font = {'size' : 16}
matplotlib.rc('font', **font)
def sqrt_sym(x):
'''A function to scale the colormap for better definition at both ends.'''
sqrt_sym = math.sqrt(x*2-1) if x > 0.5 else -math.sqrt(1-x*2)
return (sqrt_sym+1)/2
def cmap_xmap(function,cmap):
''' Applies function, on the indices of colormap cmap. Beware, function
should map the [0, 1] segment to itself, or you are in for surprises.
Third-party function. Source:
http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations
'''
cdict = cmap._segmentdata
function_to_map = lambda x : (function(x[0]), x[1], x[2])
for key in ('red','green','blue'):
cdict[key] = map(function_to_map, cdict[key])
cdict[key].sort()
'''print cdict'''
assert (cdict[key][0]<0 or cdict[key][-1]>1),\
'Resulting indices extend out of the [0, 1] segment.'
return matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)
def set_xtick(ax):
plt.xticks(np.arange(0.5,MaleSalary.NbClass+0.5,1),
('Class 1', 'Class 2', 'Class 3', 'Class 4', 'Class 5', 'Class 6') )
plt.setp([ax.get_xticklabels()[0],ax.get_xticklabels()[1],ax.get_xticklabels()[2],
ax.get_xticklabels()[3], ax.get_xticklabels()[4], ax.get_xticklabels()[5]], rotation=45,color = 'k')
def set_ytick(ax):
plt.yticks(np.arange(0.5,FemaleSalary.NbClass+0.5,1), ('Class 1', 'Class 2', 'Class 3', 'Class 4', 'Class 5', 'Class 6') )
plt.setp([ax.get_yticklabels()[0],ax.get_yticklabels()[1],ax.get_yticklabels()[2],
ax.get_yticklabels()[3], ax.get_yticklabels()[4], ax.get_yticklabels()[5]], rotation=0, color = 'k')
def autolabel(arrayA):
''' label each colored square with the corresponding data value.
If value > 20, the text is in black, else in white.
'''
for i in range(MaleSalary.NbClass):
for j in range(FemaleSalary.NbClass):
if 20.0*ContingencyTable.max()/100.0 < arrayA[i,j] < ContingencyTable.max():
plt.text(j+0.45,i+0.45, arrayA[i,j], ha='center', va='bottom',color='k')
else:
plt.text(j+0.45,i+0.45, arrayA[i,j], ha='center', va='bottom',color='w')
plotArray = ContingencyTable
fig = plt.figure()
ax = fig.add_subplot(111)
mymap = cmap_xmap(sqrt_sym,plt.cm.jet)
plt.pcolormesh(plotArray,cmap=mymap,vmin=0,vmax=ContingencyTable.max())
set_xtick(ax)
set_ytick(ax)
ax.set_xlim(0.0, FemaleSalary.NbClass)
ax.set_ylim(0.0, MaleSalary.NbClass)
autolabel(plotArray)
fig.subplots_adjust(bottom=0.27)
fig.subplots_adjust(left=0.27)
plt.title('Contingency Table')
plt.colorbar(orientation='vertical')
plt.savefig('ContingencyTable.png', bbox_inches='tight')
plt.show()
# '---------- Box Plot ----------'
data = [MaleSalary.DataValue,FemaleSalary.DataValue]
fig = plt.figure()
plt.xticks([0,1], ['Male Salary','Female Salary'])
plt.boxplot(data)
plt.savefig('BoxPlotMaleFemaleSalary.png', bbox_inches='tight')
plt.show()