Plotting Graphs + Bestfit lines

Peter Otten __peter__ at web.de
Fri Jun 13 02:33:58 EDT 2008


arslanburney at gmail.com wrote:

> Hello. Ive got two functions here. Somehow the program does not go in
> to the second function wehn i call it. The bestfit function. Could
> some1 help me identify the problem. Heres the code:

Same problem as before, you have to keep the Gnuplot instance alive if you
want to see the graph. 

Note that instead of

for i in range(len(uinput)):
    sigmaxy = uinput[i][0] * uinput[i][1] + sigmaxy

you could write

for x, y in uinput:
    sigmaxy += x * y

High time to take a look into a good Python tutorial...

# --- combine.py ---
import Gnuplot

def bestfit(uinput):
    sigmax = sigmay = sigmaxy = sigmaxwhl = sigmaxsq = 0

    for i in range(len(uinput)):

        n = len(uinput)

        sigmax = uinput[i][0] + sigmax
        sigmay = uinput[i][1] + sigmay
        sigmaxy = uinput[i][0] * uinput [i][1] + sigmaxy
        sigmaxwhl = sigmax * sigmax
        sigmaxsq = uinput[i][0] * uinput[i][0] + sigmaxsq
        sigmaxsigmay = sigmax * sigmay

        num = sigmaxsigmay - (n * sigmaxy)
        den = sigmaxwhl - (n* sigmaxsq)

        num2 = (sigmax * sigmaxy) - (sigmay * sigmaxsq)


    gradient = num / den

    intercept = num2 / den

    m = gradient
    c = intercept

    p = Gnuplot.Gnuplot()
    p.plot ('%f * x+%f'%(m,c))

    return p

def plot(original, expected, actual):
    gp = Gnuplot.Gnuplot()
    gp('set data style lines')



    # Make the plot items
    plot1 = Gnuplot.PlotItems.Data(original, title="Original")
    plot2 = Gnuplot.PlotItems.Data(expected, title="Expected")
    plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal")


    gp.plot(plot1, plot2, plot3)
    return gp


def show_plots(original, expected, actual):
    gp = combine.plot( original, expected, actual)
    raw_input("first")
    gp = combine.bestfit(expected)
    raw_input("second")
    gp = combine.bestfit(actual)
    raw_input("third")

# --- combine_main.py ---
import combine

combine.show_plots([(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5),
(5,6)], [(1,3), (3,10), (4,8), (7,9) ] )





More information about the Python-list mailing list