How do we edit xticks datetime format?

조회 수: 2 (최근 30일)
Daniel Bridges
Daniel Bridges 2017년 3월 28일
답변: Jatin 2024년 9월 5일
I am trying to increase the number of date tick marks on a graph,
but I cannot change the resulting datetime format:
Code that I think ought to work to obtain this result doesn't. I have tried the following (with a different initial datetime):
xticks(linspace(datetime('1234-11-06'),datetime('2067-04-25'),6))
xticks(linspace(datetime('06-Nov-1234','Format','yyyy-MM-dd'),datetime('25-Apr-2067','Format','yyyy-MM-dd'),5))
xticks(linspace(datetime('1234','InputFormat','y','Format','y'),datetime('2067','InputFormat','y','Format','y'),8))
xticks(linspace(datetime('1234','InputFormat','y','Format','yyyy-MM-dd'),datetime('2067','InputFormat','y','Format','yyyy-MM-dd'),8))
What is the problem? How do I increase the number of dates?
  댓글 수: 1
Steven Lord
Steven Lord 2017년 3월 28일
Which release are you using?
How did you create the plot? Did you plot with numeric or datetime X data? It can make a difference.

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

답변 (1개)

Jatin
Jatin 2024년 9월 5일
The “xticks” function you are trying to use is meant to set or query x-axis tick values, it doesn’t provide you ways to format the way tick values appear.
In your use case, If you are using a version of MATLAB R2023b or prior, you can use “datetick” which lets you specify the format you want to use in for dates. Here is an example code to use “datetick”:
% Define start and end dates
startDate = datetime('1234-11-06', 'Format', 'yyyy-MM-dd');
endDate = datetime('2067-04-25', 'Format', 'yyyy-MM-dd');
% Generate tick positions
numTicks = 6; % Adjust this number to change the number of ticks
tickPositions = linspace(startDate, endDate, numTicks);
% Example plot
figure;
plot([startDate, endDate], [0, 1]);
hold on;
% Set the x-ticks
xticks(tickPositions);
% Optionally, format the x-tick labels
ax = gca; % Get current axes
ax.XTickLabelRotation = 45; % Rotate labels if they overlap
% Display the plot
datetick('x', 'yyyy-mm-dd', 'keepticks');
From version R2024a, the function “datetick” is not recommended, you can use the function “xtickformat” which lets you configure the tick label formats for different values including dates. Here is how you can use “xtickformat”:
% Display the plot
xtickformat('yyyy-MM-dd');
You can also go through the documentation of “datetick” and “xtickformat” for more details:
Hope this helps!

카테고리

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