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

2 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 21 de Ag. de 2021
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

Más respuestas (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 20 de Ag. de 2021
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 comentarios
Image Analyst
Image Analyst el 20 de Ag. de 2021
Editada: Image Analyst el 20 de Ag. de 2021
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 el 21 de Ag. de 2021
I have attached a simple csv file. Thank you.

Iniciar sesión para comentar.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by