MATLAB: Fill, Alpha, Datenum: what is the problem

alphadatenumfill

Good morning, I am trying to plot a transparent box in a plot where the X-axis is time. I have problems when I enable the "Alpha" flag, check the piece of code I attach here. Any suggestion about a possible workaround? The problem appears only when I use timestamp, otherwise it is ok. Thanks in advance! Best regards Davide
x1 = '20-May-2015 07:28:06';
x2 = '20-May-2015 07:38:06';
x3 = '20-May-2015 07:00:00';
x4 = '20-May-2015 08:00:00';
figure();
fill([datenum(x1),datenum(x2),datenum(x2),datenum(x1)],...
0.0,0.0,5.0,5.0],1-0.3*(1-[1 0 0]),'FaceAlpha',0.5);
grid on;
hold on;
plot([datenum(x3) datenum(x4)],[0.0 .5],'.-r','MarkerSize',12,'Linewidth',2.0);
datetick('x',15,'keepticks');
axis([datenum(x3) datenum(x4) -2.0 +7.0]);

Best Answer

When you use FaceAlpha, that forces the use of the OpenGL renderer. Without it, you are getting the Painters renderer. OpenGL can have difficulty when the axis values are very close together.
If you do not need to use a DataCursor, the workaround is to shift and scale the values you use for the X axis so that they are numerically further apart, then set the XTick according to the shifted and scaled values, and then set the XTickLabel property according to what you would want the user to see at those locations. For example you might datevec() to extract the hours, minutes, seconds for the places you would like ticks, and sprintf() the parts together to get a tick label.
Related Question