How do I create a single line plot (just one line) with two differently scaled y-axes?

42 views (last 30 days)
I'm looking to create just one single line on a plot with two differently scaled y-axes--the data I need to plot is linearly converted from one value to another, so the shape of the resulting lines is identical. plotyy produces two different lines (which I don't want). Is there an easy way to do this?

Answers (3)

TastyPastry
TastyPastry on 4 Nov 2015
You can use plotyy() to plot two lines on top of each other so you only see one line. If the colors need to be the same, you can adjust them.
x = 1:100;
y = 1:100;
y1 = 101:200;
plotyy(x,y,x,y1);
  1 Comment
Brigitta Rongstad
Brigitta Rongstad on 4 Nov 2015
I have tried this, however the scales are not aligned perfectly and my lines are still slightly offset. Is there a way to make the scales align?

Sign in to comment.


Star Strider
Star Strider on 4 Nov 2015
Edited: Star Strider on 4 Nov 2015
I would set 'Visible','off' for the second line. You can do that with its handle (that you have to request as an output).
Example:
TC = 5:35;
TF = 1.8*TC + 32;
x = 1:length(TC);
figure(1)
[hax,hline1,hline2] = plotyy(x,TC, x,TF);
set(hline2, 'Visible','off')

Kelly Kearney
Kelly Kearney on 4 Nov 2015
Edited: Kelly Kearney on 5 Nov 2015
A second option would be to layer two axes manually. For example:
x = rand(100,1);
fac = 2.54;
ax(1) = axes('box', 'off');
ax(2) = axes('Position', get(ax(1), 'Position'), 'yaxislocation', 'right', ...
'xaxislocation', 'top', 'box', 'off', 'color', 'none');
hold(ax(1), 'on');
plot(ax(1), x);
ylabel(ax(1), 'Distance (in)');
ylabel(ax(2), 'Distance (cm)');
set(ax(1), 'ylim', [0 1]);
set(ax(2), 'ylim', get(ax(2), 'ylim')*fac);
The axis layering is basically the same thing plotyy does, except that plotyy chooses axis limits and tick intervals designed to align the tick marks on the two opposing axes. My example doesn't do this (which is why you need to set the 'Box' property to 'off' on both axes, or you'll get some spurious tick marks).

Categories

Find more on Two y-axis in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!