在子图中设置两个 y 轴颜色

Set two y-axis color in a subplot

在 matlab 文档中,它说可以通过执行以下操作来更改两个 y 轴图中的 Matlab 轴颜色:

fig = figure;
left_color = [.5 .5 0];
right_color = [0 .5 .5];
set(fig,'defaultAxesColorOrder',[left_color; right_color]);

y = [1 2 3; 4 5 6];
yyaxis left
plot(y)

z = [6 5 4; 3 2 1];
yyaxis right
plot(z)

这有效并产生了所需的输出。

现在我正在尝试做完全相同的图形,但在一个子图中。我的代码如下:

fig = subplot(2,1,1);
left_color = [.5 .5 0];
right_color = [0 .5 .5];
set(fig,'defaultAxesColorOrder',[left_color; right_color]);

y = [1 2 3; 4 5 6];
yyaxis left
plot(y)

z = [6 5 4; 3 2 1];
yyaxis right
plot(z)

然而,这里并没有改变坐标轴的颜色。关于如何做到这一点有什么想法吗?

您的 fig 是轴的句柄,而不是图形:

fig = subplot(2,1,1);

但是,当您设置 'defaultAxesColorOrder' 属性 时,您将其设置为其中所有轴的图形级别,如 the docs:

中所写

Set the default value at the figure level so that the new colors affect only axes that are children of the figure fig.

您需要做的就是将 fig 定义为图形,并在设置 'defaultAxesColorOrder' 属性:

后移动子图命令
fig = figure;  %<-- you change here
left_color = [.5 .5 0];
right_color = [0 .5 .5];
set(fig,'defaultAxesColorOrder',[left_color; right_color]);

subplot(2,1,1) %<-- and add that
y = [1 2 3; 4 5 6];
yyaxis left
plot(y)

z = [6 5 4; 3 2 1];
yyaxis right
plot(z)