Why does my legend have a gray background when I use it with the PLOTYY function within MATLAB?

13 views (last 30 days)
My legend have a gray background instead of white when I use it with the PLOTYY function within MATLAB.
The following code illustrates the problem:
hf = figure;
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[ax,h1,h2] = plotyy(x,y1,x,y2,'plot');
legend(h1,'first decay',2);
hl2 = legend(h2,'second decay');
Notice how the second legend has a gray background when I would expect it to be white, similar to the first one.
Now if I change the color of the legend, save the figure and load it, the changed color is not honored:
set(hl2,'Color',get(ax(1),'Color'))
hgsave(hf,'legendfig')
close(hf)
openfig legendfig

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This enhancement has been incorporated in Release 2008a (R2008a). For previous product releases, read below for any possible workarounds:
To work around this issue, try changing the background color of the legend to agree with the background color of the first plot. You can use the following code as a guide:
% Make some example data
hf = figure;
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
% Keep track of handles when plotting the data
[ax,h1,h2] = plotyy(x,y1,x,y2,'plot');
% Make the legends, and keep the handle to the legend
% that has the wrong color
legend(h1,'first decay',2);
hl2 = legend(h2,'second decay');
% Change the color so that it agrees with the first axes
set(hl2,'Color',get(ax(1),'Color'))
If you need to save the figure and reload it, then the legend's color will revert to its default. For this problem, there are no known workarounds other than changing the color again once you reload it. The following code can be used as a guide:
% Save the figure
hgsave(hf,'legendfig')
close(hf)
% Open the figure
newhf = openfig('legendfig');
% Find the legend with the bad color
% We assume the bad color is the same as the figure's color
hbadlegend = findobj(newhf,'type','axes','color',get(newhf,'color'));
% Change the color
set(hbadlegend,'color','w')

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!