how can I divide x-axis background into different colored zones?

I want to divide x-axis background into different colored\grid zones
to have a shape like this:
I use:
plot(A,B,'k');
hold on;
area(A(1:13),B(1:13),'basevalue',0,'FaceColor','g');
area(A(13:end),B(13:end),'basevalue',0,'FaceColor','r');
but it produced this shape:
I am only want to have three separate zones.
HOW CAN I DO THIS ?

 Accepted Answer

I will leave it to you to define the colours, but otherwise this code should work for you without modification in your code, except for the plot(x,y) statements:
x = linspace(0, 3E+5);
y = cumsum(rand(size(x)));
figure(1)
plot(x, y)
hold on
patch([0 1E+5 1E+5 0], [max(ylim) max(ylim) 0 0], 'r')
patch([1E+5 2E+5 2E+5 1E+5], [max(ylim) max(ylim) 0 0], 'g')
patch([2E+5 3E+5 3E+5 2E+5], [max(ylim) max(ylim) 0 0], 'b')
plot(x, y, 'k', 'LineWidth',1.5)
hold off
NOTE — You have to re-plot the original line after plotting the patches, because the patches overplot the data line. The first plot call is necessary to define the axes and the figure.

6 Comments

You can give the patches a slight negative value to have them be "under" the line. Or you can record the handle, h, of the original plot() call, and then after you draw the patch, use
uistack(h, 'top')
The second plot() is not strictly necessary.
Thank you, Walter! I managed to miss that detail in all my MATLAB explorations.
Amr Hashem can also do equivalent uistack calls (with different handle names) for his text object year labels, or just plot them once after the uistack call.
With that change, my figure code becomes:
figure(1)
h = plot(x, y, 'k', 'LineWidth',1);
hold on
patch([0 1E+5 1E+5 0], [max(ylim) max(ylim) 0 0], 'r')
patch([1E+5 2E+5 2E+5 1E+5], [max(ylim) max(ylim) 0 0], 'g')
patch([2E+5 3E+5 3E+5 2E+5], [max(ylim) max(ylim) 0 0], 'b')
uistack(h, 'top')
hold off
Also, patch() is a "primitive graphics object" and does not start a new plot so the "hold" are not actually needed there. But it is so easy to make a mistake about whether you need "hold on" or not that it is better to get into the habit of using it and only break the habit very deliberately in high-performance graphics routines.
I’m first to admit that I don’t take full advantage of all MATLAB’s myriad capabilities, and my code could be more efficient. Thank you for this and your other posts that I’ve learned from.
what if I want to replace the colors by crosshatch(3 different hatch lines)? how to do this?
See hatch.m in the File Exchange. MATLAB itself has no functions for this. Another option may be crosshatch_poly, since I used patch objects in my code. (I have no experience with either of these functions, and have not looked at their code. I can’t help you with them.)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!