Below is the code that I used to have the same scale for both y axis in MATLAB plot:
%% Additions by Dev-iL:
date = 1:10;
z = 4*randn(3,10);
spread = 0.2*sum(z,1);
figure();
%% Original code by RSerrano:
ax(2) = subplot(2,1,2);
% z = horzcat(zscore,signal1,signal2); % Dev-iL
yyaxis left
plot(date,z,'LineWidth',0.5);
ylabel('Z-score(residuals)');
set(ax(2),'YColor',[0 0 0],'YDir','normal');
ax(2).YLimMode = 'manual';
ax(2).YLim = [-8 8];
ax(2).YTickMode = 'manual';
ax(2).YTick = -8:2:8;
co1 = get(gca,'ColorOrder');
% Change to new colors.
set(gca, 'ColorOrder', [0.83 0.82 0.78; 0 0.5 0; 0.47 0.67 0.19],...
'NextPlot', 'replacechildren');
co1 = get(gca,'ColorOrder');
plot(date,z,'LineWidth',0.3);
z2 = spread;
yyaxis right
plot(date,z2,'Color',[0.31 0.31 0.31], 'LineWidth',0.5);
xlabel('Date');
ylabel('Spread(USD)');
title(['Spread and Trade Signals']);
legend('Z-score','Signal1', ...
'Signal2','Spread', ...
'Location','NE');
set(ax(2),'YColor',[0 0 0],'YDir','normal');
ax(2).YTick = -8:2:8;
axis tight
grid on
This results in:
How I can make the ylim
and ytick
of left y axis the same with right y axis? or how can I apply the ylim
and ytick
of left y axis to the right y axis?
Judging by the
yyaxis
you're using, I'd assume you have R2016a and therefore using HG2.As an alternative to
yyaxis
, assuming you just want to have the same ticks on both sides, you can just copy the axes and set the position of the y axis to be on the right (as demonstrated in a similar problem here):Using a slightly rearranged version of your code:
Here's the result:
To use with
subplot
:Here, instead of creating new axes using
axes
we might need to create them usingcopyobj
instead (this happens because theaxes
command happened to create the new axes in the correctPosition
, which is the defaultPosition
for axes; insubplot
thePosition
is not default so the previous trick doesn't work):