
で生成した PDF 画像がいくつかありますmatplotlib
。それらを任意のグリッドに配置できるようにしたいと考えています。この目的のために、LaTeX を記述して実行する Python スクリプトを作成しました。
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--images', nargs='+', help='List of images to be processed')
parser.add_argument('--output', help='Output file name', default='output_grid.pdf')
parser.add_argument('--grid', nargs=2, type=int, help='Grid dimensions (rows, columns)')
args = parser.parse_args()
return args
def main():
args = parse_args()
assert len(args.images) == args.grid[0]*args.grid[1], "Number of images does not match grid dimensions"
tex_outfile = "_{}_.tex".format(random.randint(0,100000))
with open(tex_outfile, 'w') as f:
f.write("\\documentclass[varwidth]{standalone}\n")
f.write("\\usepackage[pdftex]{graphicx, color}\n")
f.write("\\begin{document}\n")
f.write("\\begin{{tabular}}{{{}}}\n".format(" c "*args.grid[1]))
for k,v in enumerate(args.images):
f.write("\\includegraphics[width={:.9f}\\linewidth,keepaspectratio]{{{}}}".format(1.0/(args.grid[1] + 1), v))
if (k+1) % args.grid[1] != 0:
f.write(" & ")
else:
f.write(" \\\\\n")
f.write("\\end{tabular}\n")
f.write("\\end{document}\n")
os.system("pdflatex {}".format(tex_outfile))
os.system("mv {}.pdf {}".format(tex_outfile[:-4], args.output))
os.system("rm {}*".format(tex_outfile[:-4]))
上記のPythonコードは以下のLaTeXを生成し、pdflatex
Pythonコード行で実行されます。os.system("pdflatex {}".format(tex_outfile))
\documentclass[varwidth]{standalone}
\usepackage[pdftex]{graphicx, color}
\begin{document}
\begin{tabular}{ c c }
\includegraphics[width=0.333333333\linewidth,keepaspectratio]{image1.pdf} & \includegraphics[width=0.333333333\linewidth,keepaspectratio]{image2.pdf} \\
\includegraphics[width=0.333333333\linewidth,keepaspectratio]{image3.pdf} & \includegraphics[width=0.333333333\linewidth,keepaspectratio]{image4.pdf} \\
\end{tabular}
\end{document}
私が抱えている問題は、画像が完全に揃っていないことです。この画像(stackexchange 用に png に変換済み)を参照してください。
配置の問題は、y 目盛りの長さが異なることが原因だと思います。私が提供したコードでこれを修正する方法はありますか? または、より良い方法である可能性のある代替手段はありますか (subplots
個々の画像がすでに pdf として提供されているため、 は機能しません)。
答え1
左のラベルの長さが影響しないように、中央ではなく右に揃えます。また、幅ではなくスケールを使用して画像が同じ量だけ拡大縮小されるようにし、元のサイズが同じであればプロットも同じサイズになるようにします。