So I've read the two related questions for calculating a trend line for a graph, but I'm still lost.
I have an array of xy coordinates, and I want to come up with another array of xy coordinates (can be fewer coordinates) that represent a logarithmic trend line using PHP.
I'm passing these arrays to javascript to plot graphs on the client side.
Logarithmic Least Squares
Since we can convert a logarithmic function into a line by taking the
log
of thex
values, we can perform a linear least squares curve fitting. In fact, the work has been done for us and a solution is presented at Math World.In brief, we're given
$X
and$Y
values that are from a distribution likey = a + b * log(x)
. The least squares method will give some valuesaFit
andbFit
that minimize the distance from the parametric curve to the data points given.Here is an example implementation in PHP:
First I'll generate some random data with known underlying distribution given by
$a
and$b
Now, here's how to use the equations given to estimate
$a
and$b
.You may then generate points for your Javascript as densely as you like:
In this case, the code estimates
bFit = 5.17
andaFit = 9.7
, which is quite close for only50
data points.For the example data given in the comment below, a logarithmic function does not fit well.
The least squares solution is
y = -514.734835478 + 2180.51562281 * log(x)
which is essentially a line in this domain.I would recommend using library: http://www.drque.net/Projects/PolynomialRegression/
Available by Composer: https://packagist.org/packages/dr-que/polynomial-regression.