Julia: How to find best fit curve / equation when I have a plot? I have a plot which I made with map but I need to find a quadratic equation that fits this?
-
3Having a plot is irrelevant to being able to estimate coefficients for a quadratic fit. Use a 2nd order linear regression if you think that's appropriate. That said, plotting can be used diagnostically, i.e., to see if a quadratic might be appropriate. A plot is useful if you don't know the parametric form, and want to see if it might be linear, quadratic, cubic, exponential, negative exponential, hyperbolic, etc.pjs– pjs2021-01-26 03:36:05 +00:00Commented Jan 26, 2021 at 3:36
-
Have a look also to LsqFit.jl for general curve fittingAntonello– Antonello2022-04-03 20:01:39 +00:00Commented Apr 3, 2022 at 20:01
2 Answers
As said in comments, having a plot is not really relevant here; only the data itself is. You can use packages such as GLM to build (Generalized) Linear Models of your data, and possibly plot them or use them to predict new outcomes.
Here is a simple example. Let's first create sample data:
using Plots
using DataFrames
df = DataFrame(x = sort(rand(100)))
df.y = 1 .+ 2*df.x .+ 3*df.x.^2 .+ 0.1*randn(100) # y = 1 + 2x + 3x² + noise
scatter(df.x, df.y, label="data")
and build a 2nd order linear model out of it:
using GLM
model = lm(@formula(y ~ 1 + x + x^2), df) # Note how the formula looks exactly like the model you want to build
plot!(df.x, predict(model, df), label="model")
you should get something like the following:
julia> model
StatsModels.TableRegressionModel{LinearModel{GLM.LmResp{Array{Float64,1}},GLM.DensePredChol{Float64,LinearAlgebra.Cholesky{Float64,Array{Float64,2}}}},Array{Float64,2}}
y ~ 1 + x + :(x ^ 2)
Coefficients:
────────────────────────────────────────────────────────────────────────
Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95%
────────────────────────────────────────────────────────────────────────
(Intercept) 1.04201 0.0073252 142.25 <1e-99 1.02747 1.05655
x 2.04349 0.0332272 61.50 <1e-78 1.97754 2.10944
x ^ 2 2.95854 0.0321212 92.11 <1e-95 2.89478 3.02229
────────────────────────────────────────────────────────────────────────
Comments
The Polynomials package is a bit less intimidating than GLM. You can use the fit function in that package to obtain a Polynomial of best fit for any provided order (degree). Given some arbitrary (x,y) data, you can create and plot the polynomial of best fit as below.
julia> using Polynomials
julia> x=1:10;
julia> y=rand(10);
julia> quadfit=fit(x,y,2)
Polynomial(-0.06970526100724156 + 0.1638766946706202*x -0.008058423435867207*x^2)
julia> using Plots
julia> plot(x,y,label="Data")
julia> plot!(quadfit,x[1],x[end],label="Quadratic Fit")
julia> savefig("Data and Curve Fit.png")

