• Construct a Numpy array
x = array([1, 2, 3, 4, 5])
  • Elements in a Numpy array is referred just as with a list
x[-1] #-5
#array([3, 4])
  • 2D Array
x2 = array([[1, 2, 3], [4, 5, 6]])
x2[:,1] # col.1
x2[1,:] # row.1

Plot sin(x) and cos(x) with a legend

  • Start ipython with PyLab mode, and type as follows [ref]:
x = arange(-2*pi, 2*pi, 0.01)
y1 = sin(x)
y2 = cos(x)
plot(x, y1, "g:", label="$\sin(x)$") #"g:" represents green dotted line, and $\...$ denotes TeX format
plot(x, y2, "b-", label="$\cos(x)$") #"-" denotes blue dash-dot line
xlabel("$x$ (radians)")
legend() #this requires a label in plot()
savefig("fig1.eps") #save the figure as eps file

Read and Write 2D data

  • Read space-separated 2D data and plot them
data = numpy.loadtxt("temp.dat") #loadtxt() is a Numpy function; Note that pylab.load() is obsolete
plot(data[:,0], data[:,1])
  • Read data from a CSV file
data = loadtxt('temp.csv', delimiter=',', skiprows=1) #the first row contains labels