Adjusting the datetick issue.
조회 수: 4 (최근 30일)
이전 댓글 표시
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]);
댓글 수: 0
답변 (3개)
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')
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
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
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1428048/image.png)
댓글 수: 0
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);
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!