Save GUI axes with legend to jpg

1 view (last 30 days)
Kushal Bhattarai
Kushal Bhattarai on 4 Apr 2015
Answered: Philip Caplan on 13 Apr 2015
My code is able to save the axes1 plot but legend is missing on the saved file. Any help to get legend in the saved image? Any other method appreciated. I do not want to use export_fig. Using Matlab 2014a.
[filename,pathname] = uiputfile('*.jpg;*.png;*.tif','Save as');
if pathname == 0 %if the user pressed cancelled, then we exit this callback
return
end
haxes=handles.axes1;
ftmp = figure('visible','off');
new_axes = copyobj(haxes, ftmp);
set(new_axes,'Units','normalized','Position',[0.1 0.1 0.8 0.8]);
saveas(ftmp, fullfile(pathname,filename));
delete(ftmp);

Answers (1)

Philip Caplan
Philip Caplan on 13 Apr 2015
This is expected behavior because the axes object does not save an associated legend. You will need to make a separate call to "copyobj" on a legend to copy a legend to your new figure. The following code snippet illustrates this (toggle the "copyLegend" variable to determine whether the legend is copied):
close all;
copyLegend = true;
plot(1:10);
hleg = legend('myplot');
hax1 = gca;
ftmp = figure;
new_axes = copyobj(hax1,ftmp);
if copyLegend
copyobj(hleg,ftmp);
end
A legend will only appear on Figure 2 if "copyLegend" is set to true.

Community Treasure Hunt

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

Start Hunting!