2017-09-05 158 views
0

我想在Matlab中绘制一个图,其中零以下的背景区以浅红色(最后也是:淡绿色为零的区域)着色。我的代码下面出现了什么问题,以便红色矩形不会显示在图上?如果比矩形命令更方便,也欢迎向我展示另一种背景着色方法。谢谢。通过矩形绘制Matlab图的颜色背景

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); 

回答

1

您必须将矢量转换为数字。 我通常使用fill为背景着色。

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]) 

输出不是很好。也许你想给一些transparency来填充