user2861089
user2861089

Reputation: 1245

Setting the alpha value (transparency) of legend to match alpha in plot in MatLab

I've seen this question asked before but there appears to be no solution so am just wondering if it is at all possible.

I have a bar plot in MatLab and have set the transparency:

B = bar(x,y,'stacked');
set(B(1),'facecolor',[0 0.3906 0]) 
set(B(2),'facecolor',[0.5625 0.9297 0.5625])
ch1 = get(B(1),'child');
set(ch1,'facea',.5)
ch2 = get(B(2),'child');
set(ch2,'facea',.5)

And I would like the transparency in the plot to be reflected in the legend:

BL = legend ((B([1 2])),{'data1','data2'},'fontsize',10);

However, it appears the alpha value in the legend is 1.

Any ideas? Thanks.

Upvotes: 9

Views: 12733

Answers (4)

fma
fma

Reputation: 289

Apparently in the 2018b version legend takes automatically care of the transparency issue. This means you do not have to do any additional manipulation to get transparency of the legend to match transparency in the plot.

Upvotes: 0

I_am_Grand
I_am_Grand

Reputation: 106

I know this isn't code golf and the question is a bit old, but I do have an approach that is the same result in fewer lines (found it here) where you directly modify the BoxFace property instead of having to search through properties as in the two currently accepted answers.

lgnd = legend(legendTextCells);
set(lgnd.BoxFace, 'ColorType', 'truecoloralpha', 'ColorData', uint8([255;255;255;0.5*255]));

where legendTextCells is your cell array of legend text, and the alpha value can be set by modifying the decimal coefficient in 0.5*255.

Upvotes: 5

James
James

Reputation: 121

Note with the 2014b update a slight change is needed. The information about patches etc. seems now to be held in the "icons" output from the legend command, so you need;

[BL,BLicons] = legend ((B([1 2])),{'data1','data2'},'fontsize',10);

and then

PatchInLegend = findobj(BLicons, 'type', 'patch');
set(PatchInLegend, 'facea', 0.5)

for this to work now. Just spent an hour figuring this out, so thought I'd pass it on:)

Upvotes: 12

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33944

You can use PatchInLegend = findobj(BL, 'type', 'patch'); to find the patch objects in your legend. You can then set their transparency using set(PatchInLegend, 'facea', 0.5) to set their transparency.

Before Transparent

enter image description here

After Transparent

enter image description here

So the colour changes, and it does look a lot better.

Upvotes: 6

Related Questions