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
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
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.

请先登录,再进行评论。

类别

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