how to write a python program tht reads (x,y)

John Hunter jdhunter at ace.bsd.uchicago.edu
Sun May 16 10:42:33 EDT 2004


>>>>> "Selbourne" == Selbourne makhomo <smakhomo at webmail.co.za> writes:

    Selbourne> Could you please help me with the following graphs:
    Selbourne> 1. python graph that reads in (x,y) data from a file
    Selbourne> 2. modify the program to draw a graph of the function
    Selbourne> using wxpython 3. python graph that performs a linear
    Selbourne> least squares regression, which fits a straight line
    Selbourne> through the points 3. plot the straight line in a
    Selbourne> different colour to the original graph connecting the
    Selbourne> points.

    Selbourne> I will appreciate your assistance in this regard.


There are a number of ways to do it, eg, scipy contains everything you
need to do it.

Here is an example script using matplotlib.  matplotlib works with wx
(and other GUI toolkits).  I'm assuming your data are in two ASCII
columns for x and y.

    from matplotlib.matlab import *

    data  = load('xydata.dat')

    x = data[:,0]
    y = data[:,1]

    #m and b are the best bit slope and intercept
    m,b = polyfit(x,y,1)  # a line is a 1st order polynomial

    # blue dots and red solid line
    plot(x, y, 'b.', x, 3*x + b, 'r-')
    title('best fit line to noisy data')
    xlabel('x')
    ylabel('y')
    show()

You can select wx as your default in the configuration file
.matplotlibrc, or from the command line. Here is a screenshot of the
result in a wx window

  http://nitace.bsd.uchicago.edu:8080/files/share/best_fit.png

The function polyfit is defined in matplotlib.mlab (matplotlib.matlab
imports all these functions too) and does general polygon fitting .  A
line is simplest case where the order of the polygon is 1.

If you want to embed matplotlib in a wx application, rather than
simply use it from the shell or in a script, see the
examples/embedding_in_wx.py that comes with the matplotlib src
distribution.

  http://matplotlib.sourceforge.net/

Good luck!
John Hunter




More information about the Python-list mailing list