Adding transparency to one contour plot based on another contour plot

I have a contour plot, and I am looking to set the transparency of my contour plot to another variable and I cant figure out how to do this:
% color contour map
a = [1,2,3,4,5];
b = [.1, .5, 1, 2. 10];
c = a'*b;
[X,Y] = meshgrid(a,b);
figure
h = contourf(X,Y,c);
% transparency map
d = [5,4,3,2,1];
e = [10, 5, 1, 0.5, 0.1];
f = d'*e;
[U,V] = meshgrid(d,e);
figure
i = contourf(V,U,f);
I want the transparency of h to be determined by i. I can't figure out how to make this happen. FaceAlpha, AlphaData, etc are not working for me. Any help would be much appreciated!!

Answers (4)

My understanding is that this isn't supported. In the past I have done a surface plot, changed the transparancy, and then changed the view to see it from above. Here is an example.
data = rand(100,100);
surf(data,'EdgeColor','None','Facealpha',0.5);
view([0 90])
Good news! Starting in MATLAB R2022b, creating transparent contour plots is supported out-of-the-box in MATLAB.
You can adjust the transparency by setting the FaceAlpha and/or EdgeAlpha properties.
contourf(peaks,FaceAlpha=0.5)

6 Comments

While that's a big usability improvement in typical use, will the implementation allow the use of mapped alpha as this particular question requests?
Sadly, no, the new feature in R2022b only allows a single FaceAlpha for the entire contour.
@DGM how would you want to set the transparency for the faces?
  • At one end of the spectrum transparency would mirror the Z-data (lowest value is most transparent, largest value is least transparent, or vice versa) but that seems far too restrictive to be useful in most cases.
  • At the other end of the spectrum would be an AlphaData property the same size as ZData that specifies transparency at each data point. That might be more complicated to use than it is worth it, because you would need to manually bin the AlphaData based on the ZData. This also would make it difficult for the transparency to follow the contour lines, so it doesn't seem useful.
  • In the middle would be one alpha value per level, or one alpha value per face. This seems like what most people would want to use.
Is one alpha value per level sufficient or would you want one alpha value per face (so if there are two separate faces at the same level, would you ever want them to be different transparency)?
Or is there some other way you would use transparency on a contour?
The first case is possibly an occasional intent, but I see the third as the preferred generalization of it. Both could be achieved in prior versions by editing the descendant Trianglestrip objects. I've answered questions before that sought this behavior.
Disregarding the potential problems caused by aliasing, the second case is (I think) what this question is requiring. That said, I agree in that I don't think that such usage is typical or practical, as my above answer emphasizes. I was just trying to make sure there wasn't any new info that would make my answer inaccurate.
Per-triangle color/alpha spec seems terribly asbtruse. I'd struggle to find any case where it would be needed, and I'd struggle to figure out how to apply it.
I think global and per-level alpha are the only cases with practical utility, really. That's just my opinion. I don't know if per-level edge alpha would be as important as per-level face alpha, but having both would probably be best.
Hi, that is great hear from you.
i was doing some analysis on my image, during analysis my image got turn into contour. i want look my original image throgh that contour by varing FaceAlpha value. How it is possible please tell me.
i used FaceAlpha but i could not see my original image (it is just dulling contour, not making it transparent).
Thanks in advance

Sign in to comment.

mesh(___,Name,Value) specifies surface properties using one or more name-value pair arguments. For example, 'FaceAlpha',0.5 creates a semitransparent mesh plot. You can use this reference for further understanding: Mesh surface plot - MATLAB mesh (mathworks.com)
You can control the transparency of an object using the alpha function or by setting properties of the object related to transparency. Some graphics objects support using a different transparency value for the faces versus the edges of the object. Refer this link for a detailed understanding of list of objects:
You could also refer to this article, which gives an understanding of how transparency options have changed over different MATLAB versions:
​​​​​​​

4 Comments

unfortunately, none of this information answers the question
This is one way to set the alpha for each contour level.
... but if you want to make that dependent on another contourf() plot, that wouldn't work if the contour were not identical. The alpha applies to the whole Trianglestrip object that forms each contour level, which won't line up with that in a different contour map. The individual triangles won't either, and even if they did, they can't be colored individually.
I would suggest that it wouldn't really make any visual sense either. What is supposed to be under it, the other contourf() plot? If so, how would you visually interpret such a thing? Neither contour plot would correspond to its colormap anymore, because they'd be alpha blended.
So as far as I can tell, alpha mapping one contourf() plot based on an different contourf() plot isn't going to happen via the contour objects themselves. It can probably be done as an overlaid raster image of a contour map, but that sounds like a long workaround for a poor result. I could make an example, but not unless someone actually wants that.
oops, I misread the question. I was looking for a solution to make the entire contour map transparent which I need for my application. On the forums there was a easy way to do this in circa R2014 that was removed leaving only very tedious workarounds. Very happy to see the staff response indicating that it will be easy to implement starting R2022b. I agree that having transparency based on a variable seems likely to produce a difficult to read plot, but maybe OP had a good reason for it
Depending on what you need, making the entire plot transparent might be very simple, but that depends what you're trying to put under it and the relative extents of each object. A contourf over an image can be very easy if both fill the axes. It might also be a bit more cumbersome if there are different objects involved. Either way, it shouldn't require rasterization like the garbage I posted. If you still need help with it, feel free to explain what your needs are.
Yeah, answering old questions is kind of a guessing game. At some point, what OP wanted becomes less important than what passers-by want and how they interpret the question's relevance to their needs.

Sign in to comment.

I said I wasn't going to make an example, but I guess I did anyway.
% these limits must be common to both plots
% otherwise this is all just the pursuit of a meaningless colorful picture
% it kind of is anyway, but ...
xl = [1 5];
yl = [0.1 10];
% BACKGROUND PLOT
% this serves as the background and as the alpha source for the foreground
U = [5,4,3,2,1];
V = [10, 5, 1, 0.5, 0.1];
f = U'*V;
[U,V] = meshgrid(U,V);
[~,hc1] = contourf(U,V,f); % idk why axes were flipped in the original example. mistake?
xlim(xl); ylim(yl);
nlevels = numel(hc1.LevelList);
bgmap = hot(nlevels); % colormap for background plot
colormap(bgmap)
% get color copy
BG = frame2im(getframe(gca));
% get alpha copy
hc1.LineColor = 'none';
colormap(gray(nlevels)) % THIS MUST BE GRAY
box off
axis off
alphamap = frame2im(getframe(gca));
% FOREGROUND PLOT
% this is the contour map to be overlaid
X = [1,2,3,4,5];
Y = [.1, .5, 1, 2. 10];
Z = X'*Y;
[X,Y] = meshgrid(X,Y);
[~,hc1] = contourf(X,Y,Z);
xlim(xl); ylim(yl);
nlevels = numel(hc1.LevelList);
fgmap = parula(nlevels); % colormap for foreground plot
colormap(fgmap)
% get color copy
FG = frame2im(getframe(gca));
% get rid of everything
clf
% OUTPUT COMPOSITION
% set minimum and maximum alpha represented by the alphamap
alpharange = [0.5 1]; % pick your levels
alphamap = rescale(alphamap,alpharange(1),alpharange(2));
% composite the image
alphamap = im2double(alphamap); % it should already be, but just making sure
FG = im2double(FG);
BG = im2double(BG);
outpict = im2uint8(alphamap.*FG + (1-alphamap).*BG);
outpict = flipud(outpict);
% show the image with corresponding scales
image(xl,yl,outpict)
set(gca,'ydir','normal')
% set up some useless colorbars for demonstration
% colorbar scales do not yet correspond to anything
% this is just to show the impairment to visual interpretation
ax = gca;
ax2 = axes('visible','off','handlevisibility','off');
colormap(ax,bgmap);
colormap(ax2,fgmap);
% Add the two colorbars and position the main axes so that
% both colorbars fit on the right side.
cb(1) = colorbar(ax);
axPos = ax.OuterPosition;
cb(2) = colorbar(ax2);
% Split the vertical space between the 2 CBs.
cb(2).Position(4) = cb(2).Position(4)*.48;
cb(1).Position(4) = cb(1).Position(4)*.48;
cb(1).Position(2) = sum(cb(2).Position([2,4]))+.04;
cb(2).Position([1,3]) = cb(1).Position([1,3]);
ax.OuterPosition = axPos;
% Label the colorbars
ylabel(cb(1),'BG')
ylabel(cb(2),'FG')
Look at that nice crispy aliasing (part of that's the display interpolation here on the site).
Note that neither contour map can be read visually now. The shapes are mostly apparent, but neither plot can be reliably compared to its corresponding colorbar visually, and it's hard to even tell which contours belong to which plot. Note also that there need to be two colorbars, since each plot has a different colormap in this example.
The above example uses the original problem material. For a clearer visualization, let's try doing standard orthogonal unit ramps with non-overlapping colormaps.
% axis limits
xl = [0 1];
yl = [0 1];
% this is the base contour map
xy = linspace(0,1,10);
[X,Y] = meshgrid(xy,xy);
[~,hc1] = contourf(X,Y,X,20);
xlim(xl); ylim(yl);
nlevels = numel(hc1.LevelList);
whitered = makect([1 1 1],[1 0 0],nlevels); % THIS IS FROM MIMT (see file exchange)
colormap(whitered)
% get color copy
BG = frame2im(getframe(gca));
% get alpha copy
hc1.LineColor = 'none';
colormap(gray(nlevels))
box off
axis off
alphamap = frame2im(getframe(gca));
% this is the contour map to be overlaid (the foreground)
[~,hc1] = contourf(X,Y,Y,20)
xlim(xl); ylim(yl);
nlevels = numel(hc1.LevelList);
blackblue = makect([0 0 0],[0 0 1],nlevels);
colormap(blackblue)
% get color copy
FG = frame2im(getframe(gca));
% get rid of everything
clf
% set minimum and maximum alpha represented by the alphamap
alpharange = [0 1];
alphamap = rescale(alphamap,alpharange(1),alpharange(2));
% composite the image
alphamap = im2double(alphamap); % it should already be, but just making sure
FG = im2double(FG);
BG = im2double(BG);
outpict = im2uint8(alphamap.*FG + (1-alphamap).*BG);
outpict = flipud(outpict);
% show the image with corresponding scales
image(xl,yl,outpict)
set(gca,'ydir','normal')
% set up some useless colorbars for demonstration
% colorbar scales do not yet correspond to anything
% this is just to show the impairment to visual interpretation
ax = gca;
ax2 = axes('visible','off','handlevisibility','off');
colormap(ax,whitered);
colormap(ax2,blackblue);
% Add the two colorbars and position the main axes so that
% both colorbars fit on the right side.
cb(1) = colorbar(ax);
axPos = ax.OuterPosition;
cb(2) = colorbar(ax2);
% Split the vertical space between the 2 CBs.
cb(2).Position(4) = cb(2).Position(4)*.48;
cb(1).Position(4) = cb(1).Position(4)*.48;
cb(1).Position(2) = sum(cb(2).Position([2,4]))+.04;
cb(2).Position([1,3]) = cb(1).Position([1,3]);
ax.OuterPosition = axPos;
% Label the colorbars
ylabel(cb(1),'BG')
ylabel(cb(2),'FG')
So what value does this color mean? ... or should I say values, since this one color is a function of two things.
Given the uniqueness of the colormaps I chose, it could be calculated if the alpha limits are known, but if you have to resort to mathematical color analysis to read a plot, then it's not a readable plot.
Of course, that's just the example I created based on an interpretation of a dead post and a need to emphasize practical concerns. Does anyone actually want the two plots to have different colormaps, or should they be the same? Does anyone actually want to stack the two contour maps at all, or are they trying to plot one contour map over something else with an alphamap? If so, what are they plotting it over? An image? A solid color field? Some visual ambiguity might be resolvable if the background is another contour or a solid color field, but it won't be anything simple or conventional (hint: 2D colorbar). If the background is an arbitrary image, all bets are off.
If you ask me, this sounds like an XY problem, but the OP's long-past needs aside, there's no telling what 100+ people a month intend to do with their own interpretation of this question.

1 Comment

For sake of completeness, here's an example of doing the same over a solid color background.
% axis limits
xl = [1 5];
yl = [0.1 10];
% this is the base contour map
% this serves only as the alpha source for the foreground
U = [5,4,3,2,1];
V = [10, 5, 1, 0.5, 0.1];
f = U'*V;
[U,V] = meshgrid(U,V);
[~,hc1] = contourf(U,V,f); % idk why axes were flipped in the original example. mistake?
xlim(xl); ylim(yl);
nlevels = numel(hc1.LevelList);
% get alpha copy
hc1.LineColor = 'none';
colormap(gray(nlevels))
box off
axis off
alphamap = frame2im(getframe(gca));
% this is the contour map to be overlaid (the foreground)
X = [1,2,3,4,5];
Y = [.1, .5, 1, 2. 10];
Z = X'*Y;
[X,Y] = meshgrid(X,Y);
[~,hc1] = contourf(X,Y,Z)
xlim(xl); ylim(yl);
nlevels = numel(hc1.LevelList);
fgmap = parula(nlevels);
colormap(fgmap)
% get color copy
FG = frame2im(getframe(gca));
% get rid of everything
clf
% set minimum and maximum alpha represented by the alphamap
alpharange = [0.3 1];
alphamap = rescale(alphamap,alpharange(1),alpharange(2));
% show the image with corresponding scales
hi = image(xl,yl,flipud(FG));
hi.AlphaData = flipud(im2double(alphamap(:,:,1)));
set(gca,'ydir','normal','color',[1 0 0]); % set BG color
colormap(fgmap);
cb(1) = colorbar;
ylabel(cb(1),'FG')
set(gcf,'inverthardcopy',false)
saveas(gcf,'figpict.png')
So yeah. Same caveats still apply.

Sign in to comment.

Products

Tags

Asked:

on 1 Dec 2020

Commented:

on 19 Jan 2023

Community Treasure Hunt

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

Start Hunting!