fitline not displaying correct x values datetime
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
NOtway
am 26 Mai 2023
Kommentiert: Peter Perkins
am 5 Jun. 2023
I an attempting to plot a linear OLS regression line from a timetable variable that I have, however somewhere along the way the x values are getting distorted so when I plot the graph they arent at the correct date/datenum (extremely far off).
Here is what I have so far:
dates = datenum(Timetable.Time);
myfitD = polyfit(dates, Timetable.Var1, 1);
fitline = polyval(myfitD, dates);
plot(fitline);
I need to be able to add this line to an existing plot where the X axis is in datetime format.
"Timetable variable" has dates ranging from 01-Jan-2015 to 01-Jan-2099, but based on the graph its currently producing it looks to me as if the fitline is showing the correct y values at an x range of [15 90] which I dont know how to convert to be able to add to this other graph.
I've used this same method before with a similar dataset and it worked just fine, so I'm not sure what the issue is.
For additional context, the graph I am attempting to add it to is plotted as follows:
Years = {'01-jan-2030'; '01-jan-2050'; '01-jan-2070'; '01-jan-2090'};
Xaxis = datetime(Years);
scatter(Xaxis, Yvar);
x1 = datetime('01-Jan-2020');
x2 = datetime('01-Jan-2099');
xlim ([x1, x2]);
0 Kommentare
Akzeptierte Antwort
Star Strider
am 26 Mai 2023
You probably need to do centreing and scaling with your data, then use datetick to display the dates correctrly —
dates = datenum(Timetable.Time);
[myfitD,S,mu] = polyfit(dates, Timetable.Var1, 1);
fitline = polyval(myfitD, dates, S, mu);
figure
plot(dates, fitline)
datetick('x', 'keepticks', 'keeplimits')
.
1 Kommentar
Peter Perkins
am 5 Jun. 2023
datenums and datetick are not the best thing to use, but there is a version of the same idea that would use datetime: get dates as something like
dates = Timetable.Time - mean(Timetable.Time);
and then you should just be able to add Timetable.Time,fitline to the scatter plot that used a datetime axis.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Calendar finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!