Search code examples
matlabplotmatlab-figureaxissubplot

Set two y-axis color in a subplot


In the matlab documentation it says that it is possible to change the Matlab axis colors in a two y-axis figure by doing the following:

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)

This works and produces the desired output.

enter image description here

Now I was trying to do the exact same figure but in a subplot. My code is the following:

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)

enter image description here

Here, however, it does not change the axis colors. Any thoughts on how to do this?


Solution

  • Your fig is a handle to an axes, not the figure:

    fig = subplot(2,1,1);
    

    However, when you set the 'defaultAxesColorOrder' property you set it at the figure level for all axes within it, as written in 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.

    all you need to do to fix that is define fig as a figure, and move the subplot command after you set the 'defaultAxesColorOrder' property:

    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)
    

    enter image description here