필터 지우기
필터 지우기

fitline not displaying correct x values datetime

조회 수: 6 (최근 30일)
NOtway
NOtway 2023년 5월 26일
댓글: Peter Perkins 2023년 6월 5일
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]);

채택된 답변

Star Strider
Star Strider 2023년 5월 26일
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')
See the dateFormat documentation section for those details.
.
  댓글 수: 1
Peter Perkins
Peter Perkins 2023년 6월 5일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by