Adjusting the datetick issue.

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

답변 (3개)

Stephen23
Stephen23 2023년 7월 6일
편집: Stephen23 2023년 7월 6일
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
Peter Perkins
Peter Perkins 2023년 7월 17일
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.

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


Atithi
Atithi 2023년 7월 6일
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 2023년 7월 6일
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);

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by