Sunday, March 15, 2009

Curve Fitting and Plotting in Python: Two Simple Examples

Following are two examples of using Python for curve fitting and plotting. I'm using Python in a style that mimics Matlab -- although I could have used a pure object oriented style if I wanted, as the
matplotlib library for Python allows both.

Example 1: Linear Fit
import numpy
from matplotlib.pyplot import *

x = [-7.30000, -4.10000, -1.70000, -0.02564,
     1.50000, 4.50000, 9.10000]
y = [-0.80000, -0.50000, -0.20000, 0.00000,
     0.20000, 0.50000, 0.80000]

coefficients = numpy.polyfit(x, y, 1)
polynomial = numpy.poly1d(coefficients)
ys = polynomial(x)
print coefficients
print polynomial

plot(x, y, 'o')
plot(x, ys)
ylabel('y')
xlabel('x')
xlim(-10,10)
ylim(-1,1)
show()



y = 0.10160693 x - 0.02865838

Example 2: 6th Order Polynomial Fit
from numpy import *
from matplotlib.pyplot import *

x = [2.53240, 1.91110, 1.18430, 0.95784, 0.33158,
     -0.19506, -0.82144, -1.64770, -1.87450, -2.2010]

y = [-2.50400, -1.62600, -1.17600, -0.87400, -0.64900,
     -0.477000, -0.33400, -0.20600, -0.10100, -0.00600]

coefficients = polyfit(x, y, 6)
polynomial = poly1d(coefficients)
xs = arange(-2.2, 2.6, 0.1)
ys = polynomial(xs)

plot(x, y, 'o')
plot(xs, ys)
ylabel('y')
xlabel('x')
show()



y = -0.00412906x6 - 0.00160756x5 + 0.03629611x4 - 0.02020429x3 - 0.17468383x2 - 0.30660343x - 0.5139088

References
  1. Python
  2. matplotlib
  3. scipy/numpy