How can I fit a scatter plot?

조회 수: 11 (최근 30일)
Giada
Giada 2023년 3월 23일
답변: Adam Danz 2023년 3월 23일
In MATLAB, I created a scatter plot of my data with this code:
Lac = readmatrix("Lac.xlsx", "Range", "B2:Y8");
t = readmatrix("Lac.xlsx", "Range", "A2:A8");
scatter(t, Lac)
t is a 7x1 matrix; Lac is a 7x24 matrix.
How can I fit a line to this scatter plot?
  댓글 수: 1
Adam Danz
Adam Danz 2023년 3월 23일
Is your goal to fit all the data together or to fit each of the 7 groups individually?

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
Adam Danz 2023년 3월 23일
This demo shows how to plot a linera fit using the entire data.
Fitting is demonstrated using fit (Curve Fitting Toolbox) and with polyfit.
t = rand(7,1)*10;
Lac = rand(7,24)+linspace(0,2,7)';
scatter(t,Lac,'bo')
tm = repelem(t,1,size(Lac,2));
If you have the Curve Fitting Toolbox: fit()
mdl = fit(tm(:),Lac(:),'Poly1')
mdl =
Linear model Poly1: mdl(x) = p1*x + p2 Coefficients (with 95% confidence bounds): p1 = -0.1431 (-0.1796, -0.1065) p2 = 2.209 (2.005, 2.413)
hold on
plot(mdl, 'r--')
Without the Curve Fitting Toolbox: polyfit()
coefs = polyfit(tm,Lac,1)
coefs = 1×2
-0.1431 2.2089
hold on
refline(coefs(1),coefs(2))

추가 답변 (1개)

Anton Kogios
Anton Kogios 2023년 3월 23일
If you want to fit a line to the data as a whole, I think this should work:
t = 1:7;
Lac = randi(10,[7,24]);
scatter(t,Lac)
[coeffs] = polyfit(t,mean(Lac'),1)
hold on
plot(t,coeffs(1)*t+coeffs(2))
hold off
where the last argument for polyfit is the degree of the fit that you want.

카테고리

Help CenterFile Exchange에서 Get Started with Curve Fitting Toolbox에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by