Search code examples
matlabplotcolorsaxes

In Matlab, How to change axes color?


Someone, please tell me how to change the color of axes. When I run the below code, I get the time and the amplitude values on axes in black color, which is the default. I want to change its color. I have managed to change the color of the labels.

dt = 0:0.2:50;
y = 2*pi*sin(dt);
subplot(211)
plot(dt,y,'r');
grid on
xlabel('Time','color','r')
ylabel('Amplitude','color','r')
z=pi*cos(dt);
subplot(212)
plot(dt,z,'g')
grid on
xlabel('Time','color','g')
ylabel('Amplitude','color','g')

Solution

  • If you look at the documentation for subplot you'll see a syntax that allows you to store the handle to your Axes object to a variable, which you can use to specify Axes properties:

    ax = subplot(___) returns the Axes object created. Use ax to make future modifications to the axes. For a list of properties, see Axes Properties.

    Because plot (with hold off) resets the axes properties, you'll want to set the 'XColor' and 'YColor' after you have made your plots.

    For example:

    dt = 0:0.2:50;
    y = 2*pi*sin(dt);
    ax(1) = subplot(211);
    plot(dt,y,'r');
    grid on
    xlabel('Time','color','r')
    ylabel('Amplitude','color','r')
    z=pi*cos(dt);
    ax(2) = subplot(212);
    plot(dt,z,'g')
    grid on
    xlabel('Time','color','g')
    ylabel('Amplitude','color','g')
    
    set(ax, {'XColor', 'YColor'}, {'r', 'r'; 'g', 'g'});
    

    Gives us the following:

    yay