MATLAB: How to plot the same data with two y-axes on the same plot

plottingy scales

I have some error analysis that requires looking at absolute as well as percent error of some data. I toyed around with plotyy but it essentially plots the data twice with each y-axis. Anyone know how to plot the data once with one scale on the left y-axis (absolute error) and another scale on the right (percent error)
Thanks!

Best Answer

This might do what you want:
x = 0:0.1:2*pi; % Create Data
y = 50 + 10*sin(x);
figure(1)
plotyy(x,y, x,y) % PlotYY
fcyy = get(gcf, 'Children') % Gets handles for both Y-axes
Ryax = fcyy(1); % Right axis handle
Lyax = fcyy(2); % Left axis handle
Lyaxt = get(fcyy(2), 'YTick') % Get Left axis ticks
LyaxDegC = round(10*(Lyaxt-32)/1.8)/10; % Convert to °C (or whatever you want)
set(Ryax, 'YTick',Lyaxt, 'YTickLabel', LyaxDegC) % New Y-tick values
I took a while for me to figure this out. It’s necessary to use ‘gcf’ to get the handles of the two Y-axes. Then, in order to put the right Y-axis ticks at the same places as the left axis ticks, do the conversion on the left axis ticks and then plot them on the right axis. Here, I did a °F to °C conversion. I don’t know how you want to calculate your percent errors, but the ‘LyaxDegC’ line (rename it and its reference in the following line) will do it. I decided to break it out into two lines rather than do it all in the ‘set’ line to make it easier to follow.
The plotyy documentation (that I didn’t think of reading until I completed this) suggests accessing the Y-axis values as:
[hAx,hLine1,hLine2] = plotyy(x,y1,x,y2);
then referring to ‘hAx(1)’ as the left axis handle and ‘hAx(2)’ as the right axis handle. That elinimates the ‘fcyy’ line in my code. The rest of my code remains unchanged.