以下是我在MATLAB图中用于两个y轴的相同比例的代码:
%% 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
这导致:
如何使左y轴的ylim
和ytick
与右y轴相同?或者如何将左y轴的ylim
和ytick
应用到右y轴?
答案 0 :(得分:1)
根据你使用的yyaxis
判断,我假设你有R2016a,因此使用HG2。
作为yyaxis
的替代方案,假设您只想在两侧都有相同的刻度,您只需复制轴并将y轴的位置设置为右侧(如下所示)类似问题here):
hR = axes('ylim', [y(1) y(end)],'XTick', [], 'YTick', y,'YAxisLocation', 'right',...
'XTickLabel',[]);
使用稍微重新排列的代码版本:
%% Definitions:
date = 1:10;
z = 4*randn(3,10);
z2 = 0.2*sum(z,1);
y = -8:2:8;
%% Create the figure:
figure(); hL = gca;
set(hL, 'ColorOrder', [0.83 0.82 0.78; 0 0.5 0; 0.47 0.67 0.19],...
'NextPlot', 'replacechildren');
plot(date, z,'LineWidth',0.5); hold on;
plot(date, z2,'Color',[0.31 0.31 0.31], 'LineWidth',0.5);
%% Customize plots:
grid on
xlabel(hL,'Date');
ylabel(hL,'Z-score(residuals)');
hL.YLimMode = 'manual';
hL.YLim = [y(1) y(end)];
hL.YTickMode = 'manual';
hL.YTick = y;
title(['Spread and Trade Signals']);
legend(hL,'Z-score','Signal1', ...
'Signal2','Spread', ...
'Location','NE');
hR = axes('ylim', [y(1) y(end)],'XTick', [], 'YTick', y,'YAxisLocation', 'right',...
'XTickLabel',[],'Color','none');
ylabel(hR,'Spread(USD)');
linkaxes([hL,hR],'xy'); % To sync zooming, panning etc.
结果如下:
subplot
:此处,我们可能需要使用copyobj
来创建新轴,而不是使用axes
创建新轴(这是因为axes
命令恰好在正确的{Position
中创建新轴{1}},这是轴的默认Position
;在subplot
中,Position
不是默认设置,因此上一个技巧不起作用):
%% Definitions:
date = 1:10;
z = 4*randn(3,10);
z2 = 0.2*sum(z,1);
y = -8:2:8;
%% Create the figure:
figure(); subplot(2,1,2); hL = gca;
set(hL, 'ColorOrder', [0.83 0.82 0.78; 0 0.5 0; 0.47 0.67 0.19], 'NextPlot', 'replacechildren');
plot(date, z,'LineWidth',0.5); hold on;
plot(date, z2,'Color',[0.31 0.31 0.31], 'LineWidth',0.5);
%% Customize plots:
grid on
xlabel(hL,'Date');
ylabel(hL,'Z-score(residuals)');
hL.YLimMode = 'manual';
hL.YLim = [y(1) y(end)];
hL.YTickMode = 'manual';
hL.YTick = y;
hR = copyobj(hL,gcf);
hR.YAxisLocation = 'right';
title(['Spread and Trade Signals']);
legend(hL,'Z-score','Signal1', ...
'Signal2','Spread', ...
'Location','NE');
ylabel(hR,'Spread(USD)');
linkaxes([hL,hR],'xy'); % To sync zooming, panning etc.