Controlling format (number of decimals) of specific ticks
12 views (last 30 days)
Show older comments
I have a y axis running from 0 to 1 in the form of 0, 0.1, 0.2...1. I want to add an extra label, rounded to 3 decimals. By default, it's doing 4 decimals. The usual one liner to control decimals,
set(gca,'yticklabel',num2str(get(gca,'ytick')','%.3f'))
is doing it for all the points and making it ugly such as 0.100, 0.200...1.000. I just want the specific tick to have 3 decimals, not all of them. Is this possible?
0 Comments
Accepted Answer
dpb
on 21 Jun 2017
Edited: dpb
on 22 Jun 2017
figure
hAx=axes;
xtklab=get(hAx,'xticklabel');
xtklab{1}='0.000';
set(hAx,'xticklabel',xtklab)
results in
where just made arbitrary change. Obviously you can retrieve the actual tick values and convert them if don't know the actual value.
If you want to add another tick besides the default, you'll have to create those first then create the correct number of labels to match formatting them on a per each basis with the proper format string, then update.
Again, if it's known which one, doing the modification of the ticks themselves and letting the automagic labels be written first makes sense; after that just follow the above template to adjust just the one in the array wherever it is positioned.
The new axis ruler property has a 'Format' property, but it's global for the axis, not on a per tick basis.
ADDENDUM
So, for the given case...
NewTickVal=0.355; % the desired new tick value
hAx=axes;
ytk=sort([NewTickVal hAx.YTick]); % put it in the right place
hAx.YTick=ytk; % and update the tick positions
ytklab=hAx.YTickLabel; % get the new labels array
iy=find(ytk==NewTickVal); % find the one we want
ytklab{iy}=num2str(ytk(iy),'%.3f'); % and write in desired fmt
hAx.YTickLabel=ytklab; % reset labels array
The key thing to remember with tick labels vis a vis ticks is that they are NOT connected in any way whatsoever except by positional order. The label array is simply associated 1:1 in sequential order to the tick array position.
This also illustrates the use where it's convenient of the dot nomenclature for retrieving/setting properties. NB: with it, capitalization is significant where it is not with get set
8 Comments
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!