Add trend line to scatter plot with years in the X-axis

9 views (last 30 days)
I have a scatter plot with Date in the X-axis and length in Y-axis. I have been trying to add a trendline to the plot but I think because of the Date in the X-axis, polyfit or polyval are not working. Is there another way to do it?
scatter(Date, Rift)
c = polyfit(Date Rift, 1)
OR
f=fit(Date, Rift,'poly1')

Accepted Answer

Star Strider
Star Strider on 20 Oct 2022
I am not certain what the data are.
Assuming originally a datetime array and a double vector, try something lilke this —
Date = datetime(2004,01,01)+calmonths(0:1:12*16);
Rift = sin(2*pi*(1:numel(Date))/12);
[c,S,mu] = polyfit(datenum(Date), Rift, 1);
trendline = polyval(c,datenum(Date),S,mu);
figure
plot(Date, Rift)
hold on
plot(Date, trendline, '-r')
hold off
grid
.
  2 Comments
Anwesha Sharma
Anwesha Sharma on 21 Oct 2022
Thank you so much for your reply. This works perfectly.
Star Strider
Star Strider on 21 Oct 2022
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!