
我有幾張用 產生的 pdf 圖像matplotlib
。我希望能夠將它們排列在任意網格中。為此,我編寫了一個 python 腳本,該腳本依序編寫和運行 Latex。
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]))
pdflatex
上面的Python程式碼產生下面的Latex,然後在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}
我遇到的問題是圖像沒有完全對齊,請參閱此圖像(轉換為 png 以進行 stackexchange):
我認為對齊問題是由於 y 刻度長度不同造成的。有沒有辦法在我提供的程式碼中解決這個問題?或者可能是更好的方法的替代方法(使用subplots
不起作用,因為單個圖像已經以 pdf 形式提供)。
答案1
將它們右對齊而不是居中,因此左側標籤長度不會影響事物,並使用比例而不是寬度,因此圖像縮放相同的量,因此如果它們最初大小相同,則繪圖將具有相同的大小。