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

10 Ansichten (letzte 30 Tage)
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')

Akzeptierte Antwort

Star Strider
Star Strider am 20 Okt. 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 Kommentare
Anwesha Sharma
Anwesha Sharma am 21 Okt. 2022
Thank you so much for your reply. This works perfectly.
Star Strider
Star Strider am 21 Okt. 2022
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by