What command to place Horiz or Vert line best fit through points?


#1

Hi.

I have points roughly following a horizontal route and need to create a best fit horizontal (x axis) line through them.

How is this done ?

Steve


(Pascal Golay) #2

LineThroughPt will do the best fit part…

-Pascal


#3

Hi Pascal,
I tried that, but then its down to me to rotate it until its horiz then visually try to best fit it horizontally back through the points. estimating seems odd with all the mathematical methods that exist.

Steve


#4

You can try this Python script on for size… This will attempt to autodetect the most logical axis for the line to be parallel to, so in addition to X, it will also work for near Y parallel and near Z parallel groups of points…

–Mitch

(slightly edited)

BestFitLineAlongAxis.py (1.2 KB)


#5

And here is my take on the problem, and I see that I need to study Mich’s code.
For some reason the results are a bit different on complex point sets.


import rhinoscriptsyntax as rs

points=rs.GetObjects("Select points for horisontal fit",1,preselect=True)
if points:
    if len(points)>1:
        boundingbox=(rs.BoundingBox(points))
        if not boundingbox[0][0]==boundingbox[1][0]:
            line=rs.AddLine(boundingbox[0],boundingbox[1])
            #x=0
            y=0
            z=0
            for point in points:
                #x=x+rs.PointCoordinates(point)[0]
                y=y+rs.PointCoordinates(point)[1]
                y=y+rs.PointCoordinates(point)[2]
            #x=x/len(points)
            y=y/len(points)
            z=z/len(points)
            moveto=rs.CurveMidPoint(line)
            movefrom=rs.CurveMidPoint(line)
            moveto.Y=y
            moveto.Z=z
            translation=moveto-movefrom
            rs.MoveObject(line,translation)
            rs.SelectObject(line)
        else:
            print ("Error: points has the same X value")
    else:
        print ("Need more than one point")
else:
    print ("No points selected")


#6

The script tries to make Rhino do all the hard work, I use LineFitFromPoints to find the best fit line… Then I try to figure out which principal axis is the closest to parallel. Then I simply move the end points of the best fit line so that they have the same coordinates in the other two axes as the midpoint (which doesn’t move).

Edit - you could also take a different approach, that is to find the average value of all the points in X, Y and Z (that’s just the average point of the points), then run the line through that. They will give slightly different results, probably the following will be closer to yours.

BestFitLineAlongAxis2.py (1.4 KB)

–Mitch


#7

That is because " the average value" is the approach I used.

And you’ll see in this example that the midpoint approach is not a mean point if you have unevenly spaced points:

(This is an extreme example of course!)