Tutorial 3: Analysing data in Python

You could simply output your data as tab- or comma-separated text files and analyse the data in some spreadsheet package. But the matplotlib library in Python also allows for very neat and simple creation of publication-quality plots.

This script shows you how to use a couple of functions from PsychoPy® to open some data files (psychopy.gui.fileOpenDlg()) and create a psychometric function out of some staircase data (psychopy.data.functionFromStaircase()).

Matplotlib is then used to plot the data.


Matplotlib and pylab. Matplotlib is a python library that has similar command syntax to most of the plotting functions in Matlab(tm). In can be imported in different ways; the import pylab line at the beginning of the script is the way to import matploblib as well as a variety of other scientific tools (that aren’t strictly to do with plotting per se).

 1#This analysis script takes one or more staircase datafiles as input
 2#from a GUI. It then plots the staircases on top of each other on
 3#the left and a combined psychometric function from the same data
 4#on the right
 6from psychopy import data, gui, core
 7from psychopy.tools.filetools import fromFile
 8import pylab
10#Open a dialog box to select files from
11files = gui.fileOpenDlg('.')
12if not files:
13    core.quit()
15#get the data from all the files
16allIntensities, allResponses = [],[]
17for thisFileName in files:
18    thisDat = fromFile(thisFileName)
19    allIntensities.append( thisDat.intensities )
20    allResponses.append( thisDat.data )
22#plot each staircase
24colors = 'brgkcmbrgkcm'
25lines, names = [],[]
26for fileN, thisStair in enumerate(allIntensities):
27    #lines.extend(pylab.plot(thisStair))
28    #names = files[fileN]
29    pylab.plot(thisStair, label=files[fileN])
32#get combined data
33combinedInten, combinedResp, combinedN = \
34             data.functionFromStaircase(allIntensities, allResponses, 5)
35#fit curve - in this case using a Weibull function
36fit = data.FitWeibull(combinedInten, combinedResp, guess=[0.2, 0.5])
37smoothInt = pylab.arange(min(combinedInten), max(combinedInten), 0.001)
38smoothResp = fit.eval(smoothInt)
39thresh = fit.inverse(0.8)
42#plot curve
44pylab.plot(smoothInt, smoothResp, '-')
45pylab.plot([thresh, thresh],[0,0.8],'--'); pylab.plot([0, thresh],\
47pylab.title('threshold = %0.3f' %(thresh))
48#plot points
49pylab.plot(combinedInten, combinedResp, 'o')

Back to top