save several plots in seperate files within a live script

조회 수: 8 (최근 30일)
Andre
Andre 2023년 5월 23일
댓글: Walter Roberson 2023년 5월 24일
hello there,
i have a live script which plots the results at its end. it creates a new figure and title and so on. now i want to save all the figures. the figures are being created in a function, cause there is a lot of different data, but more or less the same plot.
i have found 2 solutions so far, whcih sadly dont work.
the first solution i used had the problem that it doesnt save it according to the names. they just have no name and there are overwriting each other. another problem is, that out ofnowhere it gave me the error that the folder is incorrect. i made another folder for the plots and the folder does exist, matlab knows the folder i added it.
the 2nd solution gave me the following error message
  댓글 수: 3
Walter Roberson
Walter Roberson 2023년 5월 23일
Use sprintf or compose to build a file name.
Use exportgraphics or savefig to save the plots.
Andre
Andre 2023년 5월 24일
편집: Andre 2023년 5월 24일
thats odd, i had that error seen before i had sent the post, dunno what happened
% Error using matlab.graphics.internal.name
% Unable to create output file '.\.png', Invalid argument.
% Error in print (line 71)
% pj = matlab.graphics.internal.name( pj );
% Error in saveas (line 181)
% print( h, name, ['-d' dev{i}] )
needed to comment it out, otherweise its not displayed.
exportgraphics is new for me, thanks. want to save them as jpg or png, not as fig.

댓글을 달려면 로그인하십시오.

채택된 답변

Nathan Hardenberg
Nathan Hardenberg 2023년 5월 24일
편집: Nathan Hardenberg 2023년 5월 24일
"the 2nd solution" works fine for me. You have probably edited the code wich resulted in an error. Note that you can copy and paste the itire solution (try that in a new .m or .mlx file) and do not have to change anything to get it to work.
Code from "the 2nd solution":
path = pwd ; % mention your path
myfolder = 'myfolder' ; % new folder name
folder = mkdir([path, filesep, myfolder]) ;
path = [path, filesep, myfolder];
for k = 1:10
figure(k);
plot(rand(1,10));
temp=[path, filesep, 'fig', num2str(k), '.png'];
saveas(gca,temp);
end
Your error-message seems to indicate that you have put a wrong path into the saveas()-function. Check the documentation for it for further information.
If you path is '.\.png' like the error-message suggests, your path is missing a filename. A valid path for example would be:
".\nameOfOutputFile.png"
But you have to change the filename during the loop. Otherwise your file will be overwritten (this is also done in the solution above).
  댓글 수: 3
Nathan Hardenberg
Nathan Hardenberg 2023년 5월 24일
Okay. If you edit Code and get an error, please paste it into the Question next time. How are we suppose to know what you edited and where the error comes from otherwise. Running the code without changes tests if the error ihas maybe somthing to do with your configuration.
The following Code sinppit should work to save the figures as PNG with the names "fig1.png", "fig2.png" and "fig3.png"
figure(1);
plot(rand(1,10));
figure(2);
plot(rand(1,10));
figure(3);
plot(rand(1,10));
path = pwd ; % mention your path
myfolder = 'myfolder' ; % new folder name
folder = mkdir([path, filesep, myfolder]) ;
path = [path, filesep, myfolder];
for k = 1:3 % <--- Enter right amount of figures (3 in this case)
figure(k); % select figure
temp = [path, filesep, 'fig', num2str(k), '.png'];
saveas(gca, temp);
end
From your comment I am guessing that you want to save the figures according to their name/title. While you can name them by their name, you most likely want to save them according to their title, since no name is given by default. Here is some Code (edited from your solution1) that does this. I also added functionality to check if the figure has no title and names it noTitleX.png.
figure(1);
plot(rand(1,10)); title("Test1");
figure(2);
plot(rand(1,10)); title("Test2");
figure(3);
plot(rand(1,10)); % title("Test3");
FolderName = pwd; % Your destination folder
FigList = findobj(allchild(0), 'flat', 'Type', 'figure');
for iFig = 1:length(FigList)
FigHandle = FigList(iFig);
% check if figure is internal:
if strcmp(FigHandle.Tag, 'EmbeddedFigure_Internal')
continue
end
FigName = FigHandle.Children(1).Title.String % get Title
if strcmp(FigName, '') % check if name is empty
FigName = ['noTitle', num2str(iFig)]
end
saveas(FigHandle, [FolderName, filesep, FigName, '.png']);
end
Walter Roberson
Walter Roberson 2023년 5월 24일
Recommended style changes:
figure(1);
plot(rand(1,10));
figure(2);
plot(rand(1,10));
figure(3);
plot(rand(1,10));
mypath = pwd ; % mention your path
myfolder = 'myfolder' ; % new folder name
folder = fullfile(mypath, myfolder);
if ~isdir(fullfolder); mkdir(folder); end
for k = 1:3 % <--- Enter right amount of figures (3 in this case)
figure(k); % select figure
temp = fullfile(path, "fig" + k + ".png");
saveas(gca, temp);
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andre
Andre 2023년 5월 24일
i said in a response that i did post the error, but for some reason its not been posted, it was there before i had sent the post. thats why i posted it later, but commented out, or else it would post it. i dont know what i did wrong, pretty new to that, so sorry for the inconvience.
i did tried compose and exportgraphics so and it works nicely.
function plot_PEM_gas_flow_result(Sim_CA,Sim_AN,VariableName,unit)
%plot a variable from Flow-Field Calculation for anode and cathode within
%one diagram
figure
title(VariableName)
yyaxis left
plot(Sim_CA,'DisplayName',' Cathode')
ylabel(unit)
yyaxis right
plot(Sim_AN,'DisplayName',' Anode')
ylabel(unit)
legend(Location="southoutside")
grid on
str = compose(VariableName + ".png");
exportgraphics(gca,str,"Resolution",300)
end
i also used your code just now and it works just fine. im still wondering though, why there is no name? i mean it now has one, becuase you catch the case if there is no name. isnt the name the title of the graph ? i thought so.
  댓글 수: 1
Nathan Hardenberg
Nathan Hardenberg 2023년 5월 24일
편집: Nathan Hardenberg 2023년 5월 24일
Don't confuse Name and Title. The name is given to the figure when it is initialized (see following Code). The Title is the "Title" of the Axis-object, which is a child of the figure-object. If you would initialize all figures like seen below, the code from the solution1 should work. But by default no name is given to a figure.
fig1 = figure("Name", "myName");
fig1.Name
ans = 'myName'
fig2 = figure;
fig2.Name
ans = 0×0 empty char array
And nice to see that you found a way it works for you

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Specifying Target for Graphics Output에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by