Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

plot - Positive & Negitive Log10 Scale Y axis in Matlab

Hi i'm having a problem where I have a dataset which ranges between -10^3 to 10^3

I need to be able to plot this as with a log scale but semilogy cannot plot negative values

Say for example my data is:

x = [-3,-2,-1,0,1,2,3];
y = [-1000,-100,-10,1,10,100,1000];

(or in general y=sign(x).*10.^abs(x);)

How can I plot this in MATLAB with a log scale? If possible It would be great if the log scale ticks could be on the Y-axis too

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use your actual data as labels, but scale the plotted data with log10.

% data
x = -3:0.1:3;
y = sign(x).*10.^abs(x);

% scaling function
scale = @(x) sign(x).*log10(abs(x));

N = 7;    % number of ticks desired

% picking of adequate values for the labels
TickMask = linspace(1,numel(y),N);
YTickLabels = y(TickMask);

% scale labels and plotdata, remove NaN ->inconsistency, do you really want that?
YTick = scale( YTickLabels );
Y = scale(y);

YTick(isnan(YTick)) = 0;
Y(isnan(Y)) = 0;

% plot
plot(x,Y)
set(gca,'YTick',YTick,'YTickLabels',YTickLabels)
grid on

For N = 7:

enter image description here

For N = 11

enter image description here


How to find a valid value for N?

The following function (thanks to gnovice) will return all possible values you could choose for N:

n = numel(x);
N = find(rem(n./(1:n), 1) == 0) + 1;

about the semilogy-style labels: by adding the following line before the plot:

YTickLabels = cellfun(@(x) ['10^' num2str(x)], num2cell(YTick),'UniformOutput',false)

you could at least achieve something like this: enter image description here not beautiful and not generic, but a good point to start for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...