MATLAB: Using datetime data for x axis, I have an area plot on the whole x axis and I create a fill area for [x1 x2] to highlight a specific part of the graph. Fill created is over area plot and modifies its color. So how can I have fill plot in background

1

if true
clear all
close all
clc
x = datetime(2017,01,01):datetime(2017,01,20);
y = [1,2,5,6,4,9,2,5,3,7,8,2,9,5,5,4,4,4,5,6];
x1 = datetime(2017,01,05);
x2 = datetime(2017,01,15);
area(x,y,0,'LineStyle','-','EdgeColor','g','EdgeAlpha',0.4,'FaceColor','g','FaceAlpha',0.4)
hold on
%create area on the graph to mark specific areas
yVal = ylim; %allows to fill all the y area
y1 = [yVal(1),yVal(2),yVal(2),yVal(1)]; %create variable which allows to fill all the y area whith fill fonction
fill([x1 x1 x2 x2],y1,'','LineStyle','none','FaceColor','y','FaceAlpha',0.5) %fill an area on the graph for x1/x2
end

Best Answer

Either draw the fill object at first:
fill([x1 x1 x2 x2], y1, '', ...
'LineStyle','none','FaceColor','y','FaceAlpha',0.5)
area(x,y,0,'LineStyle','-','EdgeColor','g','EdgeAlpha', 0.4, ...
'FaceColor','g')
Or use the handles:
AreaH = area(x,y,0,'LineStyle','-','EdgeColor','g','EdgeAlpha', 0.4, ...
'FaceColor','g')
FillH = fill([x1 x1 x2 x2], y1, '', ...
'LineStyle','none','FaceColor','y','FaceAlpha',0.5)
uistack(AreaH, 'top')
[EDITED] The problem is, that both objects are transparent. If you want to have one object in the backgroudn, the foreground object must be opaque. Otherwise you can see the other one through it, independent from the stacking order. Therefore I've removed the 'FaceAlpha' from the area object.