Thursday, November 14, 2013

Save Matlab Figure png same as screen appearance with annotation box

Problem: When I save matlab figures, the plots are saved distorted.
% Get screen size

scrsz = get(0,'ScreenSize');
h = figure('Position',[1 scrsz(4)/2 scrsz(3) scrsz(4)/2]);  % set figure size wrto screen size
% Position is set as  [left bottom width height]
% This is for setting fig size

h1= subplot(1,3,1);

% annotation box
p1 = get(h1,'Position');
t1 = get(h1,'TightInset');
x1 = p1(1)+t1(1); y1 = p1(4)-p1(1);
t = sprintf('R = %0.4f \ny = %0.2f + %0.2fx\nN = %i\nRMSE = %0.2f',g(1,2),p(1,2),p(1,1),length(outputs),RMSE);
% yes, I had few stuffs going on in there.  R, y=mx+c, Number of data, and RMSE
% axis   square
annotation('textbox',[x1 0.7 0.30 0.20],'String',t,'FontSize',14,'FitBoxToText','on');

h2= subplot(1,3,2);

axis([0 100 0 100])
% axis   square
p1 = get(h2,'Position');
t1 = get(h2,'TightInset');

x1 = p1(1)+t1(1); y1 = p1(4); % this will fix the annotation box

% axis   square
annotation('textbox',[x1 0.7 0.30 0.20],'String',t,'FontSize',14,'FitBoxToText','on');
% one more subplot


% Get png right for saving
% Set units
set(h, 'Units', 'centimeters')
set(h, 'PaperUnits','centimeters');
pos = get(h,'Position');

% Set paper size to be same as figure size
set(gcf, 'PaperSize', [pos(3) pos(4)]);

set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'PaperPosition', [0 0 pos(3) pos(4)]); % yes, bottom right corner!

% Print as png figure file
print(gcf, '-dpng', [fnPRE, num2str(nneurons),'-loop',num2str(i),'ipdea',num2str(testm{numvarcase})])

No comments: