3.102 FAQ-633 How to draw a line between two points to find the slope and y-intercept values?

Last Update: 2/3/2015

This LabTalk script allows the user to graphically select two data points. Once these two points are chosen, a line will be drawn between them and the slope and y-intercept values will be displayed as a text label on the graph.

def EndToolbox {
   %A=getpts.xdata$;
   %B=getpts.data$;
   slope=(%B(%A[2])-%B(%A[1]))/(%A[2]-%A[1]);
   yintercept=%B(%A[2])-slope*%A[2];
   %Z="slope=$(slope)
yintercept=$(yintercept)";
   label -p 10 0 -s -sa -n Ltext %Z;
   Ltext.background=1;
   xb1=%A[1];xb2=%A[2];yb1=%B(%A[1]);yb2=%B(%A[2]);
   draw -n Lline -l {xb1,yb1,xb2,yb2};  
   Lline.color=2;  //set color to red
   delete -v xb1;delete -v xb2;delete -v yb1;delete -v yb2;
   delete -v slope;delete -v yintercept;
   doc -uw;  //window refresh
}
getpts 2; //use data reader to select two points

The script can be run from the Script Window or put in an OGS file and then associated with a toolbar button.

Note: The script uses a dataset as a function to find the corresponding Y value for a given X value. If there are duplicate X values, then the value returned will be the Y value for the first X value found.

Keywords:LabTalk, Linear Curve Fit