Search code examples
matlabmatlab-figure

How to set background in multiple colors in semilogy plot (MATLAB) ?


I am looking for a way to shade the background of my semilog plot in two colors.
For example, in the following image, I have am plotting three polynomials and they all are equal at x=1. I want one rectangle for x<1 region and other for x>1 region. How can I insert two such rectangles, of different colors, in background to highlight these two regions.

MWE:

   x = 0.1:0.1:10;
   y1 = polyval([1, 0], x);      % Evaluate y = x;
   y2 = polyval([1, 0, 0], x);   % Evaluate y = x^2;
   y3 = polyval([1, 0, 0, 0], x);   % Evaluate y = x^3;    
   figure
   semilogy(x, y1, '.k', x, y2, '.b', x, y3, '.r');    title ('Three
   polynomials on a semilog y scale')    xlabel('x');    ylabel('y');   
   legend({'y= x', 'y = x^2', 'y = x^3'}, 'Location', 'Northwest')

enter image description here


Solution

  • You can solve that using area or patch.

    As pointed by @SardarUsama, there are others questions with good examples on it, however, you need to avoid to have any zeros in the area data, otherwise it will fail.

    Follows the code setting one area only.

    x = 0.1:0.1:10;
    y1 = polyval([1, 0], x);      % Evaluate y = x;
    y2 = polyval([1, 0, 0], x);   % Evaluate y = x^2;
    y3 = polyval([1, 0, 0, 0], x);   % Evaluate y = x^3;    
    figure
    plot(x, y1, '.k', x, y2, '.b', x, y3, '.r'); %MODIFIED   
    hold on  %ADDED
    title ('Three  polynomials on a semilog y scale')   
    set (gca, 'Yscale', 'log'); %ADDED
    xlabel('x');   
    ylabel('y');   
    legend({'y= x', 'y = x^2', 'y = x^3'}, 'Location', 'Northwest')
    
    area( [1 1 10 10],[1e-3 1e+3 1e+3 1e-3 ],'FaceColor','green','facealpha',0.3)  %ADDED
    

    The code above works for matlab after 2014b. If you have one before that, you can use the patch function (which requires some small change in the data, but uses the Facealpha option) or you can move the area to the background as i do below:

    ax=get(gca,'Children'); %ADDED
    set(gca,'Children',[ax(2) ax(3) ax(4) ax(1)]); %ADDED, move area to background
    

    Note: Indeed, I missed the problem with the legend. I correct as mentioned, however for me the area was on top of the other graphs. To solve it i changed the order of the plots. If the area was with transparency, this will not be an issue.