7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MATLAB plotのpdf保存

Posted at

MATLABのplotで作ったグラフをpdfに保存する方法について書いてみます。
グラフをpdfで欲しいという人は、LaTeXを使う人くらいかと思いますので、ここではLaTeXを使う人を想定しています。

exportgraphics コマンドを使う (R2020a以降)

ヘルプセンター exportgraphics

R2020a以降が使えるのであれば、exportgraphicsを使うのが一番簡単です。

sineWave.m
%%
x = 0:1e-2:2*pi;
y = sin(x);

%%
fig_h = figure;
po1 = plot(x, y);
xlabel("x")
ylabel("y")
legend("sin(x)")
ax = gca;
ax.FontName = "Helvetica";
ax.FontSize = 14;
ax.XLim = [0, 2*pi];
ax.YLim = [-1.2, 1.2];

%%
exportgraphics(gca, "sineWave.pdf");

対象となるオブジェクトがaxisで、figureハンドラではないことに注意が必要です。
(saveasはfigureハンドラを指定します。)

sineWave.png

saveas + pdfcropを使う (要 LaTeX環境)

R2020aより以前ではsaveasを使うのがひとつの手です。
saveasでpdfに保存できるのですが、問題があります。
グラフ領域だけでなく、A4ページまるまると出力されてしまう点です。

ですので、補助ツールとしてpdfcropを使います。pdfcropは余白を調整するツールです。
pdfcropはTeXLiveに含まれています。

MATLABスクリプトで処理するには、例えば下のようにします:

saveas(fig_h, "sineWave1", "pdf")
pdfcropCOM = "c:/path/To/pdfcrop.exe";
system(pdfcropCOM + " sineWave1.pdf sineWave1-crop1.pdf")

pdfcropはかなりギリギリのところで切り取ります。マージンを指定するには

saveas(fig_h, "sineWave1", "pdf")
pdfcropCOM = "c:/path/to/pdfcrop.exe";
system(pdfcropCOM + " --margins ""8 8 8 8"" sineWave1.pdf sineWave1-crop2.pdf")

のようにすれば良いです。--marginの後の数字はお好みで。

pdfcropの中身

pdfcropコマンドの実体はPerlスクリプトです。
中の処理はTeX Wiki/pdfcropによれば

  • Ghostscriptでバウンディング・ボックスを取得
  • 仮のLaTeX文書を生成して、対象のpdfファイルを画像として取り込む。この時に上記のバウンディング・ボックスを利用する。
  • pdflatexで pdfとして出力する

とのことです。ですのでLaTeX環境がひと通り必要です。一筋縄ではいかない…。

export_figを使う (要 Ghostscript)

MathWorks File Exchange/export_figというツールが公開されています。
これでダイレクトに適切な大きさのpdfを出力できます。

(2009年くらいから公開されているようです。)

export_fig("sineWave3.pdf", fig_h)

export_fig の中身

pdfを出力する際のexport_figの中では、まずepsに出力してGhostscriptを呼び出すようです。
だからGhostscriptが必要なのですね。

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?