Difference in the behavior of transparency in R2015a and R2016a

1 view (last 30 days)
I tried to use the following code to draw three rectangles, filled with different colors, overlapping each others.
x = [-1 1 1 -1 -1 ];
y = [-1 -1 1 1 -1];
hold on
fill(x*3,y*3,'b','facealpha',0.2)
fill(x*2,y*2,'g','facealpha',0.2)
fill(x,y,'r','facealpha',0.2)
This is what I expected:
This is what I got from both MATLAB R2015a and R2016a:
After some research online, I figured out that the issue in R2016a is because of the SortMethod of the axes, so I added this code:
set(gca,'SortMethod','depth')
The one in R2016a becomes what I expected. However no change in R2015a. How can I get the same result as R2016a?

Answers (1)

Benjamin Kraus
Benjamin Kraus on 27 Jul 2018
The effect you see is because the patches overlap one another. The red patch overlaps both the green and the blue patch, so you are seeing the merged colors of the three patches. This is the expected behavior.
This blog post talks about SortMethod. I get the same behavior in R2015a as R2016a when I change the sort method to depth, but the issue is that you are not specifying the Z-data for the patches (you are using fill not fill3), so I think it is somewhat arbitrary which patch gets rendered on top or bottom (it probably depends in part on your graphics card and drivers).
To correct way to get the desired result is to not have overlapping patches, or to specify the color value and not have transparency.
Based on your expected result, you don't really want transparency, but you really just want specific colors that look faded. Transparency will allow the bottom patches to show through the top patches. You can guarantee your desired behavior this way:
x = [-1 1 1 -1 -1 ];
y = [-1 -1 1 1 -1];
hold on
fill(x*3,y*3,'b','FaceColor',[0.8 0.8 1])
fill(x*2,y*2,'g','FaceColor',[0.8 1 0.8])
fill(x,y,'r','FaceColor',[1 0.8 0.8])
  2 Comments
Woody
Woody on 30 Jul 2018
Thanks Benjamin for the reply. Actually I need to overlay these patches on top of a map-like image, hence the transparency is required. I will try with the fill3 function and see how I can get the patches showing the correct color with transparency showing the image below them.
Woody
Woody on 30 Jul 2018
This is a simplified version of what the actual application should look like, the rectangles are actually contour line generated by the "contour" function.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!