Adjusting the datetick issue.

5 Ansichten (letzte 30 Tage)
peter huang
peter huang am 6 Jul. 2023
Kommentiert: Peter Perkins am 17 Jul. 2023
x is a sequence from 2005 to 2023 with a step of every two years. y represents my calculated results, and I'm using sine values as a substitute. I want to use the range from 2003 to 2023 for the x-axis. So, I used the xlim function to adjust the x-axis. However, I want both the start and end of the x-axis to show 2003 and 2023. How can I achieve this?
Below is my sample code:
clear all ; clc ;clf
set(gcf,'color','w')
load m_time_1516.mat
%%
%%
x = 1 : 9
y = sin(x)
m_time_1516(1) =[]
plot(m_time_1516 ,y)
datetick('x','yyyy' )
s_time = datenum('01-01-2003')
e_time = datenum('01-01-2023')
xlim([s_time ,e_time]);

Antworten (3)

Stephen23
Stephen23 am 6 Jul. 2023
Bearbeitet: Stephen23 am 6 Jul. 2023
Do not use deprecated DATENUM or serial date numbers or the like.
Use DATETIME (and set the format if required):
S = load('m_time_1516.mat')
S = struct with fields:
m_time_1516: [0 7.3268e+05 7.3341e+05 7.3414e+05 7.3487e+05 7.3560e+05 7.3633e+05 7.3706e+05 7.3779e+05 7.3852e+05] s_time_1516: [0 732313 733043 733774 734504 735235 735965 736696 737426 738157]
X = datetime(S.m_time_1516(2:end), 'ConvertFrom','datenum');
Y = sin(1:numel(X));
plot(X,Y)
xlim(datetime([2003,2023],1,1))
You might find this useful too:
  1 Kommentar
Peter Perkins
Peter Perkins am 17 Jul. 2023
Stephen and Kevin have the right advice: don't use datenums (or these days, even datetick). Convert to datetime at the earliest point in your code.

Melden Sie sich an, um zu kommentieren.


Atithi
Atithi am 6 Jul. 2023
By adding the xticks and xticklabels functions, you can set explicit tick locations and labels for the x-axis. In this case, we set the tick locations to [s_time, e_time] and the tick labels to {'2003', '2023'}. This ensures that both the start and end of the x-axis display the desired years.
clear all; clc; clf
set(gcf, 'color', 'w')
load m_time_1516.mat
x = 1:9;
y = sin(x);
m_time_1516(1) = [];
plot(m_time_1516, y)
datetick('x', 'yyyy')
s_time = datenum('01-01-2003');
e_time = datenum('01-01-2023');
xlim([s_time, e_time]);
xticks([s_time, e_time]); % Set explicit tick locations
xticklabels({'2003', '2023'}); % Set tick labels
Do let me know if it worked for you, I am attaching my code output below.

Kevin Holly
Kevin Holly am 6 Jul. 2023
clear all ; clc ;clf
set(gcf,'color','w')
load m_time_1516.mat
x = 1 : 9;
y = sin(x);
m_time_1516(1) =[];
plot(datetime(m_time_1516,'ConvertFrom','datenum') ,y)
% s_time = datenum('01-01-2003')
% e_time = datenum('01-01-2023')
xlim([datetime('1-Jan-2003'),datetime('1-Jan-2023')])
h=gca;
h.XTick =datetime(2003,1,1):calyears(1):datetime(2023,1,1);

Community Treasure Hunt

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

Start Hunting!

Translated by