Home > front end >  How can I build custom xticklabels using numbers and strings?
How can I build custom xticklabels using numbers and strings?

Time:07-23

I am trying to customize the Xticklabels of my bar graph to have a format of 'number (units)'

So far I have a vector:

scanrate = [2;4;6;8;10];

I want my bar graph to have an x axis of:

2mv/s 4mv/s 6mv/s 8mv/s 10mv/s

If I use xticklabels(num2str(scanrate)) the xticklabels change to the numbers in the scanrate vector. I want to put mv/s after each Xtick.

CodePudding user response:

You can also use strcat :

xticklabels(strcat(num2str(scanrate),' mv/s'))

Please note that it works only when scanrate is a column vector.


Fun fact :

num2str(scanrate)   " mv/s"

also works, but

num2str(scanrate)   ' mv/s'

does not

CodePudding user response:

Build your strings using sprintf(), where the %d flag is for an unsigned integer:

my_labels = {};
for ii = 1:numel(scanrate)
    my_labels{ii} = sprintf('%dmv/s', scanrate(ii));
end

figure;
% (...) make your plot
xticklabels(my_labels)

Alternative one-liner, thanks to Wolfie's comment:

my_labels = arrayfun(@(x)sprintf('%dmv/s',x),scanrate,'uni',0);

As a side note: that's normally not what you'd do when creating these type of plots. You'd just have numbers on the axes and a label stating something as "Velocity [mv/s]", rather than having the unit on every single tick label.

  • Related