MATLAB R2025b "savefig(...)" fails to save changed legend Position when existing .fig file is opened and edited.
26 views (last 30 days)
Show older comments
Heinz-Bernd Schuttler
on 12 Oct 2025 at 7:41
The question is explained in detail in the attached .txt file. Briefly:
Assume some figure A.fig was created by some plot(..) commands etc. and was then saved with only one single legend and legend box position coordinates [xO yO wO hO], the _old_ coordinates, with assumed values like, say,
[xO yO wO hO] == [0.7 0.6 0.2 0.3 .
From that A.fig, I now want to generate a new version, B.fig, which displays the legend box with _new_ position coordinate values, [xN yN wN hN], given by
[xN yN wN hN] == [0.6 0.5 0.3 0.4] ,
all else being the same as in A.fig.
The problem I run into is this:
I open A.fig, look up the legend handle (call it "hL") and change the legend box position coordinates by hL.Position=[xN yN wN hN]; hL.Location='none'; save it as B.fig by savefig('B.fig') and then close all. If I then later (re-)open B.fig, I find that B.fig has been saved with the old legend position coordinates [xO yO wO hO], instead of the new ones, [xN yN wN hN].
1 Comment
Accepted Answer
dpb
ungefär 19 timmar ago
Edited: dpb
ungefär 12 timmar ago
% create and save an original plot with legend at 'Northeast' location
hL=plot(0:10,rand(11,3));
hLg=legend(compose('Line %d',1:3));
title('Figure A')
hLg.Position % show the position vector is right, top
saveas(gcf,'FigureA') % ok, save this one as 'A'
close 1 % close the window, clear variables
clear % so no remnants of old remain
open('FigureA.fig') % reload friend 'A'
hLg=findobj(gcf,'type','legend'); % get the legend and reset location to SW
hLg.Location='southwest';
hLg.Position % show is now at left, bottom
title('Figure B') % give it another identifier if legend is worong place
saveas(gcf,'FigureB') % and save, close so can't be confused with what get from disk
close
clear
open('FigureB.fig') % and get new buddy, 'B'
The above code does the desired set of operations and does, in fact, return the figure with the changed location of the legend.
Your actual sequence of operations is inadvertently saving the original Figure 1 again although we can't see where the logic error in the code may be because you didn't show us the precise code run; only a description of what you intended the code to have done.
As the above shows, you have to be sure you are actually saving the correct, modified figure after the changes were made.
0 Comments
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!