plotyy : align y axes at zero

When using plotyy I need to plot two different series. One on the left y axis, and the other on the right y axis. Both series contain numbers in different scales. The one of the left contains numbers from 0 to (potentially) Infinity, but the one on the right is restricted to the range -1, 1. In the code below, you can see an example.
I'd like to make sure that both axes cross at y = 0, but I'm not sure how to do it. In the example I included, you can see that the two y axes are misaligned.
Thanks in advance
x = 15;
fn1 = @(x, y) bar(x, y, 0.3, 'FaceColor', 'blue');
fn2 = @(x, y) bar(x, y, 0.3, 'FaceColor', 'red');
figure;
plotyy( [1:x]-1, rand(x, 1) * 100, [1:x]+1, 2 * rand(x, 1) - 1, fn1, fn2)

 Risposta accettata

Oleg Komarov
Oleg Komarov il 25 Feb 2012
A quick fix, call plotyy as:
ax = plotyy(...)
Then set limits of axes
set(ax(1),'Ylim',max(get(ax(1),'Ylim')) * [-1 1])
EDIT General solution with ratio of negative leg over positive
% Retrieve Ylim of second axis
ylim2 = get(ax(2),'Ylim');
% Ratio of negative leg to positive one (keep sign)
ratio = ylim2(1)/ylim2(2);
% Set same ratio for first axis
ylim1 = get(ax(1),'Ylim');
set(ax(1),'Ylim',[ylim1(2)*ratio ylim1(2)])

1 Commento

Mark
Mark il 25 Feb 2012
First of all, thanks for taking the time to read and answer my question.
The example I put was simply for simplification purposes. Although the range of the secondary axes is [-1, 1], the numbers I plot may not cover all that range. For instance, in the example I used, the second series with the following:
[ax, ~, ~] = plotyy( [1:x]-1, rand(x, 1) * 100, [1:x]+1, (-0.2:(0.8--0.2)/(x-1):0.8), fn1, fn2)
Then use your fix and you will see that it doesn't solve the problem. if you set the limits of the secondary axes to [-1, 1]:
set(ax(2),'Ylim',[-1 1])
Then the axes are aligned at zero but there is a huge amount of space between y=0, and y=-1
I was looking for a more general solution. In my particular case, the negative values are rare but when they happen they are usually closer to 0 than to -1. Conversely, the positive values can be up to zero, but they usually are less than 0.9.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by