Saving plots in For loop
1 view (last 30 days)
Show older comments
When I am using the below command, it is giving me error as invalid or missing path.
saveas(gcf,['Monthly plot for: ', datestr(Yr_Avg.dd(j)), '.png'])
0 Comments
Accepted Answer
Siraj
on 4 Jul 2022
Edited: Siraj
on 4 Jul 2022
Hii,
It is my understanding that you are getting the mentioned error (error1.PNG) beacuse your are including the special character ":" (colon) in your file name, which is not allowed. If you remove the colon and just leave a blank space after "for", the code will work fine.
I am attaching the 2 valid ways of using "saveas()".
Hope it helps.
curr_fig1 = figure();
x = linspace(-2*pi,2*pi,100);
y = sin(x);
figure(1);
plot(x,y);
t = datetime(2022,11,30);
% saveas(curr_fig1,strcat("Monthly plot for ", datestr(t)), "png") % First Way
saveas(curr_fig1,['Monthly plot for ', datestr(t), '.png']) % Second Way
More Answers (2)
Image Analyst
on 4 Jul 2022
baseFileName = sprintf('Monthly plot for %d.png', datestr(Yr_Avg.dd(j))); % Don't use banned characters like colons and slashes.
folder = pwd; % Wherever you want.
fullFileName = fullfile(folder, baseFileName);
fprintf('Saving plot : %s\b', fullFileName);
exportgraphics(gca, fullFileName); % Save current graph. Or use gcf if you want the entire figure.
2 Comments
Image Analyst
on 4 Jul 2022
for k = 1 : numFigs
hFig = figure; % Create a new figure.
for k2 = 1 : 6
subplot(3, 2, k2);
% make your graphs
end
% Now all 6 graphs have been made on a new figure so save
% the entire figure of 6 graphs as one single image.
baseFileName = sprintf('Monthly plot for %d #%d.png', datestr(Yr_Avg.dd(j)), k); % Don't use banned characters like colons and slashes.
folder = pwd; % Wherever you want.
fullFileName = fullfile(folder, baseFileName);
fprintf('Saving plot : %s\b', fullFileName);
exportgraphics(hFig, fullFileName); % Save current graph. Or use gcf if you want the entire figure.
% Close down this figure after it's been saved.
close(hFig);
end
See Also
Categories
Find more on Printing and Saving 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!