MATLAB Answers

Modifying Figure Y-Axis Exponent Parameter After YTickLabels are Modified

5 views (last 30 days)
Innocentio Loe
Innocentio Loe on 21 May 2020
Commented: Innocentio Loe on 22 May 2020
Hello,
simply put, I have a figure in which I want to mark a certain YTickLabels as text, instead of value.
It all goes well, but by doing so, the exponent marker on the Y-Axis is gone. Forcing to set the value of 'Exponent' property of the YAxis doesn't work either. I guess it's because the Y-Axis ruler now has both number and text, so there is no proper scaling there.
I wonder if there is any workaround to this. Of course it is possible to add the exponent manually later, but I kind of want to have a procedural method for consistency.
The code below will demonstrate what I meant.
% Plot Data
figure(1);
t = linspace(0,1,100);
y = 0.005*sin(2*pi/0.01*t);
plot(t,y);
hold on;
plot(xlim,[0 0],'k--');
grid on;
% Adding a line of interest
yval = 0.001;
plot(xlim,[yval yval],'k-');
hold off;
% Modify YTicks to Min-Y, 0, YVal, Max-Y
yticks = get(gca,'YTick');
yticks = sort([min(yticks),0,yval, max(yticks)],'ascend');
% Modify YTickLabels
ylabels = get(gca,'YTickLabel');
ylabels(3) = {'YVal'};
set(gca,'YTickLabel', ylabels);
set(get(gca,'YAxis'),'Exponent',-3); %--> This doesn't work now

  0 Comments

Sign in to comment.

Accepted Answer

dpb
dpb on 21 May 2020
Edited: dpb on 21 May 2020
Don't use manual labels on ticks, just don't put ticks at the unwanted places. When write labels, the EponentMode is set to 'Manual' and then the exponent display goes away.
hL=plot(t,y);
hold on
yline(yval)
yl=ylim;
yticks([yl(1) 0 yl(2)])
hTxt=text(-0.01,yval,'YVal','HorizontalAlignment','right');
produces
BTW, you alias the MATLAB builtin yticks function above; don't do that! Makes high probability of coding errors later when want to use it.
Another alternative would be to not try to futz with the axis label but use the annotation/label of the yline object instead. It will be on the line inside the graph area but doesn't require the other manipulations to not write the one tick value. And, if yval isn't some nice even number always, that doesn't match up nicely with where tick marks logically go, it isn't affected.
A possible enhancement request for the yline object might be an 'outside' position key value--altho it raises the problem of potential clash with tick labels but a smart implementation could deal with it.

  1 Comment

Innocentio Loe
Innocentio Loe on 22 May 2020
Hello,
thank you very much, that worked like a charm. I thought the "text" function was only useful to put things inside the figure axes, but turns out it can write outside the bounds too.
Thanks for pointing out the issue with "yticks" variable as well.

Sign in to comment.

More Answers (0)


Translated by