简体   繁体   中英

Color background of Matlab plot via rectangle

I want to draw a plot in Matlab where the background area below zero is colored in light red (and eventually also: the area above zero in light green). What is wrong with my code below so that the red rectangle doesn't show up on the plot? You're also welcome to show me another way to color the background if more convenient than the rectangle command. Thank you.

Y = [];
for year = 2008:2016
    Y = vertcat(Y,[year;year]);
end
M = repmat([01;07],9,1);
D = [01];
vector = datetime(Y,M,D);

figure;
rectangle('Position',[0,-2e4,length(vector),2e4],'FaceColor',[1 0 0],'EdgeColor',[1 0 0]);
hold on;
plot( vector, [-2e4, -1e3, -5, -100, 5, 20, 100, 40, -20, -200, -600, -2, 30, 80, 200, 800, 1500, 2500], 'LineWidth',1.2 ), grid on;
dateaxis('x', 12);

You have to convert vector to a number. I usually use fill to color the background.

figure;hold on
fill([2008 2016 2016 2008 ],...
[-2e4 -2e4 0 0],'r');
fill([2008 2016 2016 2008 ],...
[0 0 3e3 3e3],'g');
plot( str2num(datestr(vector,'yyyy')), ... %%%convert vector format
[-2e4, -1e3, -5, -100, 5, 20, 100, 40, -20, -200, -600, -2, 30, 80, 200, 800, 1500, 2500], ...
'LineWidth',1.2 ), grid on;
axis([2007 2019 -2e4 3e3])

The output is not very nice. Maybe you want to give some transparency to fill

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