Adjusting the datetick issue.

5 次查看(过去 30 天)
peter huang
peter huang 2023-7-6
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 中查找有关 Grid Lines, Tick Values, and Labels 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by