How does one display the fit line in this plot in this situation?
4 次查看(过去 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?
0 个评论
采纳的回答
Sulaymon Eshkabilov
2021-8-21
T = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/717514/test.csv');
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
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
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 Center 和 File Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!