Force exponential format of ticks LIKE MATLAB does

2020-07-10 07:24发布

问题:

I have two plots. In the first plot the values for the y-axis go up to 30000. Therefor, Matlab is labeling the axis instead of '30000' with '3' and the 'x10^4' ABOVE the plot. In the second plot the y-values just go til 10000. Due to the fact that this value is too low to automatically switch to exponential format it really prints '10000'.

I would like to know if there is a way to force the exponential formatting. This will result in THE SAME FORMAT as Matlab does it automatically. I am asking this because I have seen solutions where you can make Matlab print '10^3' directly as Y-label, but I just want to have it show '1' as Label and the 'x10^3' above the plot.

The following image shows to different plots merged together just for the purpose of clarifying my question. In the left half of the image you can see what Matlab does if I am using values > 10000. And that's the kind of format I want to get for the axis shown in the second half if the image below.

回答1:

I just get here because I need something similar, and I know that now there is a solution for that. Perhaps from R2015 and newer, you can set the exponent excatly with:

ax.YAxis.Exponent = 3  % 3 is for example

Or, if you want the full numbers:

ax.YAxis.Exponent = 0

While ax is the axis handle.



回答2:

It doesnt appear to be possible based upon some reading, testing and property checking:

http://www.mathworks.com/matlabcentral/answers/8005-axes-tick-in-scientific-notation

The scientific notation label will only automatically appear if you have not set the YTickLabel property. If you set YTickLabel, then there is no (documented) way to get MATLAB to automatically put in the exponent the same way.

In order to get around this, if you set YTickLabel and you want the exponent, you need to text() the exponent where you want it to appear.

You can format the y axis labels like so

set(gca,'YTickLabel',sprintf('%3.1f|',get(gca,'ytick')/max(get(gca,'ytick'))

Then add the x 10^4 with TeX markup ('$\times10^4$') to get the same result manually.



回答3:

For me, using the '$[TeX]$' syntax doesn't work (R2012a). Instead, texlabel() works.

However, Matlab doesn't allow TeX interpreting in axis labels (at least not 2012a, and the help for 2013a doesn't seem promising: e.g. set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})

Here is a workaround, where you make your own labels by using the text() function.

plot(1:9,exp(-[1:9]))
set(gca,'XTick',[1 3 5 7 9],'XTicklabel',[])
arrayfun(@(x)text(x-.1,-.02,texlabel(sprintf('e^%d',x))),[1 5 9],'UniformOutput',false)