MATLAB: MATLAB fail to create Chart with Multiple x-Axes and y-Axes

plotyyaxis

Dear all, the objective was to two x-Axes and y-Axes. However, I am unable to produce the intended graph even follow the MATLAB Example. The 2 signals does not overlap into each other, instead one of the signal cover entirely the first signal that being plot.
I really appreciate if someone can point what I have been missing. Thanks in advance
The following code has been used but without success.
load('st_data.mat');
figure
errorbar(st_X_hour, st_Vec_Y1_mean, st_Vec_Y1_Sd, '--x','MarkerSize',15)
ax1 = gca; % current axes
set(ax1, 'Xtick', st_Xaxis_intrmit, 'XTickLabel',st_XLabel,'XAxisLocation','top'); xtickangle(90)
ax1_pos = ax1.Position; % position of first axes
ax2 = axes('Position',ax1_pos,'XAxisLocation','top','YAxisLocation','right', 'Color','none');
plot(st_X_hour,st_Y2,'Parent',ax2,'Color','k')

Best Answer

When ax2 is created, by default its NextPlot property is set to 'replace'. When the next graphics operation is done (the plot call), the graphics system sees that replace is in effect, and does a cla(), which leaves position the same but happens to reset the Color property back to the default [1 1 1].
You can deal with this by,
ax2 = axes('Position', ax1_pos, 'XAxisLocation', 'top', 'YAxisLocation', 'right', 'Color', 'none', 'NextPlot', 'add');
or you can deal with it by
hold(ax2, 'on')
before doing the plot().
But do not just deal with it by
set(ax2, 'Color', 'none')
after doing the plot(), as the cla that was done on your behalf also reset the axis locations.