Saving graph from GUI as .fig works, but not as .png

In my GUI i have an axes with some random plot in it. I am trying to save this graph as a figure and as a .png by pressing a button. I already know that in order to save the axes only (not the whole GUI window), i have to create a new figure, and then use COPYOBJ to copy that axes to the new figure. This is where I got the idea and code from. It looks like this:
fignew = figure('Visible','off'); % Invisible figure
newAxes = copyobj(handles.axes1,fignew); % Copy the appropriate axes
set(newAxes,'Position',get(groot,'DefaultAxesPosition')); % The original position is copied too, so adjust it.
set(fignew,'CreateFcn','set(gcbf,''Visible'',''on'')'); % Make it visible upon loading
set(fignew, 'PaperPositionMode', 'auto');
print(fignew,filename,'-dpng')
%export_fig(fignew, filename); %using export_fig as a second option as it is recommended often
savefig(fignew,[filename,'.fig']);
While the saved figure looks perfectly fine,
the .png files look like this:
by using export_fig and the following one by using print:
As you can see in the first image, the graph is squeezed to a very small size and sits in the bottom left corner. The rest is white space only. The second image consits of the small size graph only. I don't know what is happening there.
I appreciate every bit of help and want to thank you for taking your time reading this.

 Réponse acceptée

gummivogel
gummivogel le 6 Juil 2018
Modifié(e) : gummivogel le 6 Juil 2018
My mistake. I didnt know that the units of my axes are set to pixels when creating it. Adding the line
set(handles.axes1,'units','normalized')
solved my problems.

Plus de réponses (1)

Jan
Jan le 5 Juil 2018
Modifié(e) : Jan le 5 Juil 2018

0 votes

Please try to insert a drawnow command. It seems, like the new figure is not updated correctly, when it is created with Visible='off'.
What happens if you run this with a visible figure?

Catégories

En savoir plus sur Printing and Saving dans Centre d'aide et File Exchange

Produits

Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by