# Plot 3 lines using plotyy with Different X-axis

1 view (last 30 days)
Sheikh Imran on 10 Jan 2022
Answered: dpb on 10 Jan 2022
I want to draw 3 lines that are related to each other But when using the code below, The graphic appears as layers, and the legend is not correct. What is the correct way to write this code? . I use MATLAB R2013a. `
figure ('Name','Booster Energy ,Horizental Beam Size & Vertical Beam Size')
[hax,hLine5,hLine6] = plotyy(bo_time_data,bo_energy_data,vsize_time,vsize);
[Hax,hLine7,hLine8] = plotyy(bo_time_data,bo_energy_data,hsize_time,hsize);
grid on
set(Hax(1),'YTick',0:150:1000);
set(Hax(2),'YTick',0:0.2:5);
set(hLine5,'LineStyle','-');
set(hLine5,'color','black');
set(hLine6,'LineStyle','-');
set(hLine6,'color','red');
set(hLine7,'LineStyle','-');
set(hLine7,'color','black');
set(hLine8,'LineStyle','-');
set(hLine8,'color','green');
title('Booster Energy ,Horizental Beam Size & Vertical Beam Size')
xlabel('t(ms)')
ylabel(Hax(1),'Energy(MeV)') % left y-axis
ylabel(Hax(2),'Beam Size (mm)') % right y-axis
legend ('Booster Energy','Vertical Beam Size','Horizental Beam Size');`
a

dpb on 10 Jan 2022
plotyy creates two overlaying axes; you've created two sets of those and there's no way to not occlude one axis with the other, depending which you give focus.
Probably the simplest way is to just use hold on and add to the RH axes...
figure ('Name','Booster Energy ,Horizental Beam Size & Vertical Beam Size')
[hAx,hLL,hLR] = plotyy(bo_time_data,bo_energy_data,vsize_time,vsize); % the first data sets
hold(hAx(2),'on') % prepare add to RH
hLR=[hLR; ploty(hAx(2),hsize_time,hsize); % add the second line
...
Now add the legends, etc., to the two axes as needed/desired.
If the two RH time datasets are the same length, you could plot them together in one call as
[hAx,hLL,hLR] = plotyy(bo_time_data,bo_energy_data,[vsize_time(:) vsize_time(:)],[vsize(:) hsize(:)]);
which by the (:) ensures they are column vectors to catenate.

R2013a

### Community Treasure Hunt

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

Start Hunting!

Translated by