# Plotting Graphs + Bestfit lines

Peter Otten __peter__ at web.de
Fri Jun 13 10:43:00 CEST 2008

```arslanburney at gmail.com wrote:

>> > Still confused though i get the instance part ur trying to tell me.

> Tried that out too. No error however, best fit lines still not being
> made on the graph. Only the 3 plot lines show up.

Gave it another shot. You might want something like

from __future__ import division
import Gnuplot

def bestfit(uinput, **kw):
sigmax = sigmay = sigmaxy = sigmaxsq = 0

for x, y in uinput:
sigmax += x
sigmay += y
sigmaxy += x * y
sigmaxsq += x * x

n = len(uinput)
sigmaxwhl = sigmax * sigmax
sigmaxsigmay = sigmax * sigmay
num = sigmaxsigmay - n * sigmaxy
den = sigmaxwhl - n * sigmaxsq
num2 = sigmax * sigmaxy - sigmay * sigmaxsq

intercept = num2 / den

return Gnuplot.Func('%f * x+%f' % (gradient, intercept), **kw)

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="Actual")
bf2 = bestfit(expected, title="Best fit expected")
bf3 = bestfit(actual, title="Best fit actual")

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

if __name__ == "__main__":
gp = plot( [(2,3), (4,8), (5,9), (6,2)], [(1,7), (3,3), (4,5), (5,6)],
[(1,3), (3,10), (4,8), (7,9) ] )
raw_input()

It's all in one file for simplicity. Note that I did not check the best fit