1
votes

In a Matlab plot I define my x-axis as a preaccumulated array timeInSec:

y = data;
x = timeInSec;
plot(x , y);

The generated x-axis on the plot looks like this:

enter image description here

The ticks and tick-values (the 0, 0.5, 1, 1.5, 2 and 2.5) here are auto-generated by Matlab. And I am happy with them.

But now I would like to change the tick-value labels customly. Something like:

timeInHrMin = datestr(tickValues, 'HH:MM')
xticklabels(timeInHrMin)

But how do I grab all shown tickValues? I need them to remain auto-generated. So I must in some way grab only those shown (the 0, 0.5, 1, 1.5, 2 and 2.5) and relabel them with xticklabels.

Is this possible?

1

1 Answers

0
votes

Yes, it is possible.

You can grab all shown tick values either by using get(gca,'XTick') as was suggested by Sardar Usama or by accessing property CurrentAxes.XTick of your figure.

As for relabeling, there is one small yet important/annoying detail regarding using xticklabels. Once you use it, ticks are no longer automatically generated. In order to solve it you can use xtick('auto') just before grabbing and modifying the labels.

I'm also guessing that you want to have the ticks refreshed when you zoom in/out. You can do it using zoom and its callbacks.

Code below should make it all clear:

function so
    % meaningless data to have some ticks
    fs = 48000;
    t = 5;
    tvect = 0:1/fs:t-1/fs;
    a = sin(2*pi*tvect);

    % plotting data
    fig = figure;
    plot(tvect, a)

    % modifying the ticks for the first time after creating the plot
    mypostcallback(fig, struct('Axes', fig.CurrentAxes));

    % modifying post zoom callback
    h = zoom(fig);
    h.ActionPostCallback = @mypostcallback;
end

function mypostcallback(obj,evd)
    % turning on auto generation of ticks after previous usage of xticklabels
    xticks('auto')
    % part where you modify tick labels however you want. 
    % In my case simply adding 10 to the original values.
    xticklabels(evd.Axes.XTick + 10)  
end