homelist of postsdocs about & FAQ

A basic "seed" for plotting csv data files with matplotlib.

Well, basically all the usage guide and information about the matplotlib library is available online, however I am writing this as an emphasis on how good matplotlib actually is, moreover I can again use this short snippet as a quick "seed/template" in the future without having to write it from scratch. Here's a short example on plotting line charts from a *.csv file.

## Plotting from a csv and writing down a pdf using matplotlib. Look after the transpose function for the column plotting settings.
##
## Initial verison A Deyan Levski - didolevski@gmail.com
##
##

from numpy import array
import csv
import matplotlib.pyplot as plt

#def plotit(filename,title):

filename='Slew-Rate-Limit-Errors-Capture.csv';
title='OTA residue voltage';

cs=csv.reader(file(filename,"r"),delimiter=",")# seperator of csv data is a tab ("\t")
# Have to convert comma decimal to dot decimal delimiter
# newlist=[[float(e.replace(".",".")) for e in x] for x in cs]
#If no conversion needed paste in: newlist=[[float(e) for e in x] for x in cs]
newlist=[[float(e) for e in x] for x in cs]
# convert from  pairs for [[x1,y1],[x2,y2]...etc] to [x1,x2,..] [y1,y2,..]

ar=array(newlist).transpose()

fig=plt.figure()

ax.plot(ar[0],ar[1])
ax.plot(ar[0],ar[3])
ax.set_xlabel(r"$T_{p}$")
ax.set_ylabel(r"Voltage")

ax.grid(True)  # Default grid settings
#ax.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)

#ax.axis('tight') # Tight auto axis

ax.set_ylim([-0.5, 4]) # Custom Y axis
#axes[2].set_xlim([2, 5]) # Custom X axis

plt.title(title) # Plot

plt.savefig(filename+".pdf") # Save figure

One can also use it for plotting histograms, e.g. if you are running some MonteCarlo simulations directly from the SPICE engine and you do not have any GUI available to use.

## Plotting from a csv and writing down a pdf using matplotlib. Look after the transpose function for the column plotting settings.
##
## Initial verison A Deyan Levski - didolevski@gmail.com
##
##

from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)

from numpy import array
import csv
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

#def plotit(filename,title):

filename='OTA-InputOffset-MC-4000.hash';
title='OTA Input Offset Distribution';

cs=csv.reader(file(filename,"r"),delimiter=",")# seperator of csv data is a tab ("\t")
# Have to convert comma decimal to dot decimal delimiter
# newlist=[[float(e.replace(".",".")) for e in x] for x in cs]
#If no conversion needed paste in: newlist=[[float(e) for e in x] for x in cs]
newlist=[[float(e) for e in x] for x in cs]
# convert from  pairs for [[x1,y1],[x2,y2]...etc] to [x1,x2,..] [y1,y2,..]

ar=array(newlist).transpose()

fig=plt.figure()

# the histogram of the data
n, bins, patches = ax.hist(ar[1], 30, normed=1, facecolor='green', alpha=0.75)
# hist uses np.histogram under the hood to create 'n' and 'bins'.
# np.histogram returns the bin edges, so there will be 50 probability
# density values in n, 51 bin edges in bins and 50 patches.  To get
# everything lined up, we'll compute the bin centers
bincenters = 0.5*(bins[1:]+bins[:-1])

acc=0
nr=0
for i in ar[1]:
acc += i
nr += 1

mu=acc/nr
print mu

acc2=0
nr=0
for i in ar[1]:
acc += ((i-mu)**2)
nr += 1

sd=acc/nr
sd=math.sqrt(abs(sd))
print sd

# add a 'best fit' line for the normal PDF
y = mlab.normpdf( bincenters, mu, sd)
l = ax.plot(bincenters, y, 'r--', linewidth=1)

ax.set_xlabel('Input offset voltage')
ax.set_ylabel('Run')

ax.set_xlim(-0.05,0.05)
#ax.set_ylim(0, 0.03)
ax.grid(True)
plt.title(r'Input offset voltage variation $\mu$=%.3f, $\sigma$=%.3f' %(mu, sd))
plt.savefig(filename+".ps") # Save figure
plt.show()

#ax.plot(ar[0],ar[1])
#ax.plot(ar[0],ar[3])
#ax.set_xlabel(r"$T_{p}$")
#ax.set_ylabel(r"Voltage")

#ax.grid(True)  # Default grid settings
#ax.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)

#ax.axis('tight') # Tight auto axis

#ax.set_ylim([-0.5, 4]) # Custom Y axis
#axes[2].set_xlim([2, 5]) # Custom X axis

#plt.title(title) # Plot

#plt.savefig(filename+".pdf") # Save figure 

Here is a link to the "seed" folder. Where generated pdf graps can also be found.

Date:Sun Mar 09 12:46:50 CEST 2014