简体   繁体   中英

How to set background color for specific x-values of plot in Matlab?

Eg see below.

I'd like to color-code (in red) the years for which another independent timeseries is greater than 0.

在此输入图像描述

You can use the patch() function to draw sqares wherever you want, and give it the color in RGBA format, using an A (alpha) of around 0.5 for example

Lets illustrate with an example:

x=1:0.1:10;
y=sin(x*2*pi);

box1=[1 1 2 2];
box2=[4 4 5 5];
boxy=[-1 1 1 -1]*max(y)*1.2;

plot(x,y)
patch(box1,boxy,[0 1 0],'FaceAlpha',0.2)
patch(box2,boxy,[1 0 0],'FaceAlpha',0.2)

ylim(1.1*[min(y) max(y)])

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM