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

4 ビュー (過去 30 日間)
alpedhuez
alpedhuez 2021 年 8 月 20 日
コメント済み: alpedhuez 2021 年 8 月 21 日
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 Center および File ExchangeLinear and Nonlinear Regression についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by