Clear Filters
Clear Filters

Modify the labels an axis in plot

4 views (last 30 days)
Joel on 4 Apr 2023
Answered: Neha on 4 Apr 2023
I have a 8760x1 double (TIMVARDEN). One value for each hour of the year.
I typed
This is the month of January expressed in hours.
However, I want the x-axis to be expressed in days. I also want the label to show the date and time as the X value.
So instead of
X 348
I want
X '15-Jan-2021 11:00'
Y 171.24

Accepted Answer

Ganesh Gudipati
Ganesh Gudipati on 4 Apr 2023
Hi Joel,
You can use the function 'datetime' and generate sequence of Dates and time. Save that generated value to 'x' and plot the graph now. You should be able to see your expected output.
You can refer the below code
t1 = datetime(2015,1,1,0,0,0); %start point (year, month, date, hours, mins, seconds)
t2 = datetime(2015,1,31,23,0,0);%end point
x = t1:hours(1):t2; %generate date and time between t1 and t2 (Jan 1 to Jan 31 - 744 hours)
y = [1:744]; %replcae the value of 'y' with TIMVARDEN(1:744,1)
The result will look like this
I hope this resolves your query.

More Answers (1)

Neha on 4 Apr 2023
It is my understanding that you need to perform the following tasks:
  • The X-axis should be expressed in days.
  • The format of the datatip output should be changed.
To express the X-axis in days:
for i=1:32
For the second part of the question:
  • Right click on the data-tip
  • Select "Update Function"
  • Then, select "Edit"
You can replace the existing code with the code below:
function output_txt = myfunction(obj,event_obj)
% Display data cursor position in a data tip
% obj Currently not used
% event_obj Handle to event object
% output_txt Data tip text, returned as a character vector or a cell array of character vectors
pos = event_obj.Position;
%********* Define the content of the data tip here *********%
% Display the x and y values:
output_txt = {['X',formatValue(string(datetime(2021,1,1)+hours(pos(1))),event_obj)],...
% If there is a z value, display it:
if length(pos) > 2
output_txt{end+1} = ['Z',formatValue(pos(3),event_obj)];
function formattedValue = formatValue(value,event_obj)
% If you do not want TeX formatting in the data tip, uncomment the line below.
% event_obj.Interpreter = 'none';
if strcmpi(event_obj.Interpreter,'tex')
valueFormat = ' \color[rgb]{0 0.6 1}\bf';
removeValueFormat = '\color[rgb]{.25 .25 .25}\rm';
valueFormat = ': ';
removeValueFormat = '';
formattedValue = [valueFormat num2str(value,4) removeValueFormat];
After pasting the above code, you can save the file as myfunction.m.
The plot will look like the below image:


Find more on Dates and Time in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!