MATLAB:在主要和次要 y 轴之间切换的更好方法?

MATLAB: a better way to switch between primary and secondary y-axis?

我知道 plotyy,但在我看来,它不像输入 subplot(2,3,1) 那样直观,从那时起,在那个特定的子图环境中工作...

假设我有以下数据:

a=rand(20,1);
a_cumul=cumsum(a);

我想在主要(左手)y 轴上绘制 plota_cumul,在辅助(右手)y 上绘制 a 的条形图-轴。

我很清楚我能做到:

plotyy(1:length(a_cumul),a_cumul,1:length(a),a,'plot','bar')

但这很麻烦,如果我只想绘制到次要 y 轴而不绘制到主要 y 轴怎么办?简而言之,我正在寻找是否存在这样的解决方案:

figure;
switchToPrimaryYAxis; % What to do here??
plot(a_cumul);
% Do some formatting here if needed...
switchToSecondaryYAxis; % What to do here??
bar(a);

非常感谢您的帮助!

基本上plotyy:

  • 创建两个叠加的axes

  • 在第一个轴上绘制指定为前两个参数的数据

  • 在第二个轴上绘制指定为最后两个参数的数据

  • 将第二个坐标轴颜色设置为 none 使其 "transparent" 以便在第一个坐标轴上查看图表

  • yaxislocation从标准位置(左)移动到右

您可以创建一个 figure,然后创建两个 axes make make 在两个 axes 上创建任何 plot,方法是选择 then with axes(h) where h 是轴的处理程序。

然后您可以编写自己的函数来执行坐标轴调整。

用于创建 figureaxes 并调用调整轴的函数的脚本

% Generate example data
t1=0:.1:2*pi;
t2=0:.1:4*pi;
y1=sin(t1);
y2=cos(t2);
% Create a "figure"
figure
% Create two axes
a1=axes
a2=axes
% Set the first axes as current axes
axes(a1)
% Plot something
plot(t1,y1,'k','linewidth',2)
% Set the second axes as current axes
axes(a2)
% Plot something
plot(t2,y2,'b','linewidth',2)
grid
% Adjust the axes:
my_plotyy(a1,a2)

调整轴的功能 - 模拟 plotyy 行为

该函数需要两个轴的句柄作为输入

function my_plotyy(a1,a2)

set(a1,'ycolor',[0 0 0])
set(a1,'box','on')
% Adjust the second axes:
%    change x and y axis color
%    move x and y axis location
%    set axes color to none (this make it transparend allowing seeing the
%       graph on the first axes

set(a2,'ycolor','b')
set(a2,'xcolor','b')
set(a2,'YAxisLocation','right')
set(a2,'XAxisLocation','top')
set(a2,'color','none')
set(a2,'box','off')

希望这对您有所帮助。