簡介
在寫文章的時候,時常用到Matlab來繪製圖形,以更好的說明自己的想法。一般的方法是將Matlab繪製的figure另存爲png或者jpeg格式的圖像然後將這些圖像放到自己的文檔中。不管是放到word裏還是用過Latex來排版,都面臨一個問題:Matlab繪製的區域在整個圖像的中間區域且與邊緣相差一些像素。我們可以手動剪切這些多餘的邊緣,但是,如果圖像變多了,或者需要重新繪製圖形了,每次都手動操作確實讓人反感。這裏我們用在繪製的時候加一段程序來將我們需要的圖形區域填充整個圖像,並用程序自動保存圖像。
程序演示
寫一段程序來演示一下這個功能。
for i = 1:4
% plot a figure
figure;
x = normrnd(0, 3, [100, 3]);
hist(x);
legend({'$C_1$', '$C_2$', '$C_3$'}, 'Interpreter', 'latex', 'Location', 'NorthEast');
xlabel('\textbf{Variabel} $x$', 'Interpreter', 'latex');
ylabel('\textbf{Count}', 'Interpreter', 'latex');
title(['Figure ', num2str(i)]);
% specify figure size
af = gcf;
af.Position(3) = af.Position(3)*0.7;
af.Position(4) = af.Position(4)*0.5;
% expand axes to fill figure
ax = gca;
outerpos = ax.OuterPosition;
ti = ax.TightInset;
left = outerpos(1) + ti(1);
bottom = outerpos(2) + ti(2);
ax_width = outerpos(3) - ti(1) - ti(3);
ax_height = outerpos(4) - ti(2) - ti(4);
ax.Position = [left bottom ax_width ax_height];
% Specify Page Size
af.PaperPositionMode = 'auto';
fig_pos = af.PaperPosition;
af.PaperSize = [fig_pos(3) fig_pos(4)];
% save the figure
print(af, ['Figure_', num2str(i), '.png'], '-dpng');
end
結果如下圖所示:
上面的圖像是直接將保存後的圖像上傳的,四個圖像的尺寸完全相同。並且沒有多餘的空白邊緣,無需進一步剪切圖像。