Modify the labels an axis in plot
Show older comments
I have a 8760x1 double (TIMVARDEN). One value for each hour of the year.
I typed
plot([1:744],TIMVARDEN(1:744,1))
ylabel('kW')

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
Y171,24
I want
X '15-Jan-2021 11:00'
Y 171.24
Accepted Answer
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
xt(i)=(i-1)*24;
xtl(i)=i-1;
end
plot([1:744],TIMVARDEN(1:744,1));
xticklabels(xtl);
xticks(xt);
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)],...
['Y',formatValue(pos(2),event_obj)]};
%***********************************************************%
% If there is a z value, display it:
if length(pos) > 2
output_txt{end+1} = ['Z',formatValue(pos(3),event_obj)];
end
%***********************************************************%
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';
else
valueFormat = ': ';
removeValueFormat = '';
end
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:

Categories
Find more on Annotations 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!