How does one display the fit line in this plot in this situation?

조회 수: 3 (최근 30일)
I have a timetable T with
T.date T.vistors T.sales
----------------------------------------
I draw a plot
yyaxis left
plot(T.date, T.visitors)
hold on
yyaxis right
plot(T.date, T.sales)
Now I want to add a regression line of T.sales = a + b*T.visitors on this plot.
But this situation seems to be more complex. How to proceed?

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 8월 21일
T = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/717514/test.csv');
Warning: The DATETIME data was created using format 'MM/dd/uuuu' but also matched 'dd/MM/uuuu'.
To avoid ambiguity, supply a datetime format using SETVAROPTS, e.g.
opts = setvaropts(opts,varname,'InputFormat','MM/dd/uuuu');
fit_model = polyfit(T.Visitor, T.Sales,1);
TSales_Fit = polyval(fit_model,T.Visitor);
yyaxis left
plot(T.Date, T.Visitor, 'ro', 'markerfacecolor', 'c', 'markersize', 13)
hold on
yyaxis right
plot(T.Date, T.Sales, 'bs', 'markerfacecolor', 'y', 'markersize', 9)
hold on
plot(0:numel(TSales_Fit)-1,TSales_Fit, 'k-', 'linewidth', 2)
legend('Date vs. Visitors', 'Date vs. Sales', 'Fit model: Visitors vs. Sales', 'location', 'northwest')
grid on

추가 답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 8월 20일
You can use these additional steps to get the linear fit model and calculate its values, and then plot them.
fit_model = polyfit(T.visitors,T.sales,1);
TSales_Fit = polyval(fit_model,T.visitors);
yyaxis left
plot(T.date, T.visitors)
hold on
yyaxis right
plot(T.date, T.sales)
hold on
plot(T.visitors, TSales_Fit)
Note that your set x -axis is T.date and what you are trying to plot on top of that is T.visitors (x-axis) vs. Tsales_Fit (y-axis). There is a mismatch. Thus, it is more appropriate to compute fit model: DD=datenum(T.date); TSales_Fit = a + b*(DD-DD(1)+1); and plot the followings:
DD=datenum(T.date);
DD = DD-DD(1)+1;
fit_model = polyfit(DD,T.sales,1);
TSales_Fit = polyval(fit_model,DD);
yyaxis left
plot(T.date, T.visitors)
hold on
yyaxis right
plot(T.date, T.sales)
hold on
plot(T.date, TSales_Fit)
legend('Date vs. Visitors', 'Date vs. Sales', 'Fit model: Date vs. Sales', 'location', 'best')
  댓글 수: 3
Image Analyst
Image Analyst 2021년 8월 20일
편집: Image Analyst 2021년 8월 20일
Please attach your table T in a .mat file with the paper clip icon if you need any more help. Otherwise we're just guessing.
alpedhuez
alpedhuez 2021년 8월 21일
I have attached a simple csv file. Thank you.

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

카테고리

Help CenterFile Exchange에서 Axis Labels에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by