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.
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!